Introduction to Python
using sage
Sage + Python = Awesomeness
First things first:
Tabbing & Questions
If you don't know what a function does, type the function, add a ? and hit tab for a quick description.
Try typing:
fibonacci?
Second:
Data Types
Luckily there are a finite number of data types in Python. This list includes- Booleans
- Integers
- Floats
- Strings
- Sets
- Lists
- Tuples
- Dictionaries
type
function. Or you can ask directly if the object is of a certain type using isinstance
.Full details can be found in the python docs.
Booleans
bool
has one of two values: True
and False
.
There are three boolean operators: and
, or
, & not
.
You can convert something into a boolean by the bool
function.
Integers/Floats
int
is the python built-in integer type. The problem with the python version is the integer conversion problem.
Due to this restriction, Sage uses its own type called Integer
.
float
is the python built-in rational number type. Due to similar restrictions, Sage uses the RealLiteral
type.
Strings
The str
type is fairly common. You can use single or double quotes. Additionally you can use triple quotes if you want a multi-line string. You can also fill a string using dictionary substitutions as can be seen in the following example.
Sets, lists, tuples, and dictionaries
Because, why not.
set
- is a set of items with no multiplicites or order.list
- is an ordered list of itemstuple
- is the same as a list, but it is immutable (it cannot be changed).dict
- Is an associative array which associates values with keys.
Some basic commands
Constructing stuff
How many stuff does it have?
Use thelen
function.Is this object present?
Use thein
operator.Note: The
in
operator for dictionaries looks at the keys!How do I access elements?
Use square brackets to access individual items. For dictionaries you use the key. For lists and tuples the counting begins at . Sets have no order so you can't "access" things.Can I modify things?
Only lists and dictionaries! Tuples are immutable, so they can't be altered.How do I add new things?
There are many ways my young padawan.
Sets - Use the add
function
Lists - You can append
a list at the end, extend
a list with another list, or just plain add two lists together.
Tuples - They are immutable, so we can't alter them! We can add two of them together and create a new tuple though.
Dictionaries - Just add a new key and put in a value.
Russell's paradox
Sets of sets can't happen
But I added too much! How do I delete things I don't want?
Some other useful commands (Lists only!):
sort
reverse
Some basic commands
Operation | set |
list |
tuple |
dict |
---|---|---|---|---|
Construction | set([]) |
[] |
() |
{} |
One element construction | set([1]) |
[1] |
(1,) |
{1:1} |
Size | len(set) |
len(list) |
len(tuple) |
len(dict) |
Contains | x in set |
x in list |
x in tuple |
key in dict |
Accessing entries | - | list[0] |
tuple[0] |
dict[key] |
Adding stuff | set.add(x) |
list.append(x) list.extend(list2) list3 = list1 + list2 |
tuple3 = tuple1 + tuple2 |
dict[key] = x key must be immutable |
Deleting stuff | set.discard(item) |
list.pop(i) del list[i] list = list[start:end] list.remove(value) |
tuple = tuple[start:end] |
dict.pop(key) del dict[key] |
- Create the list
[5,1,3,6,7,2,12]
. - Remove the element 12.
- Add the element 4.
- Sort the list and reverse it.
The modification problem.
Or things that should be illegal.
Changing lists and dictionaries can have unintended consequences.Stop this nonsense! How do we fix this?
deepcopy
to the rescue!
The None
type
If you want to set a variable but don't want to set it as any particular type, you can use None
Ranges
Lists made easy
Ranges allow us to make numerical lists easily. We use the range
function to construct a range.
range
to construct the list of even numbers between and (including ).Bonus: Put it in reverse order.
Third parts the charm:
Control Flows
if
- Does something if the condition is true.for
- Loops through a range of objects.while
- Keeps looping until condition is false.
Quick aside: Comparisons
or
and
not
- Boolean operators==
- Equal!=
- Not equal<
>
<=
>=
- Inequalitiesis
- Object identityis not
- Negated object identity
if
with its siblings elif
and else
.
for
for
loop to print out all the non-even primes from to .
while
for
and list
The super team
We can use for loops in order to create super awesome lists.Wait, it gets better.... Nesting!
We can nest these lists in order to construct lists of tuples, dictionaries, matrices, etc.These special lists also allow us to grab the keys/values of dictionaries!
Integers vs ints
Revisited
Part :
Functions
Functions are defined using thedef
statement. We can return things from functions using the return
keyword.Recursion - Catalan Numbers
Complicated recursion - Catalan Numbers part 2
Functions can also have default values.
Functions can also return multiple values if desired.
Digraphs!
Sage allows us to construct digraphs using dictionaries. Let's take a sidestep and look at how to construct digraphs and some operations we can do on them.