This tutorial is an introduction to basic programming in Python and Sage, for
readers with elementary notions of programming but not familiar with the Python
language. It is far from exhaustive. For a more complete tutorial, have a look
at the Python Tutorial. Also Python’s
documentation and in particular the
standard library can be
useful.

In Python, typing is dynamic; there is no such thing as declaring variables.
The function type() returns the type of an object obj. To convert an
object to a type typ just write typ(obj) as in int("123"). The
command isinstance(ex,typ) returns whether the expression ex is of
type typ. Specifically, any value is an instance of a class and there is
no difference between classes and types.

The symbol = denotes the affectation to a variable; it should not be
confused with == which denotes mathematical equality. Inequality is !=.

The standard types are bool, int, list,
tuple, set, dict, str.

The type bool (booleans) has two values: True and False. The
boolean operators are denoted by their names or, and, not.

The Python types int and long are used to
represent integers of limited size. To handle arbitrary large
integers with exact arithmetic, Sage uses its own type named
Integer.

A list is a data structure which groups values. It is constructed using
brackets as in [1,3,4]. The range() function creates integer
lists. One can also create lists using list comprehension:

[<expr>for<name>in<iterable>(if<condition>)]

For example:

sage: [i^2foriinrange(10)ifi%2==0][0, 4, 16, 36, 64]

A tuple is very similar to a list; it is constructed using
parentheses. The empty tuple is obtained by () or by the
constructor tuple. If there is only one element, one has to
write (a,). A tuple is immutable (one cannot change it) but it
is hashable (see below). One can also create tuples using
comprehensions:

sage: tuple(i^2foriinrange(10)ifi%2==0)(0, 4, 16, 36, 64)

A set is a data structure which contains values without
multiplicities or order. One creates it from a list (or any
iterable) with the constructor set. The elements of a set
must be hashable:

A dictionary is an association table, which associates values to
keys. Keys must be hashable. One creates dictionaries using the
constructor dict, or using the syntax:

{key1:value1,key2:value2...}

For example:

sage: age={'toto':8,'mom':27};age{'mom': 27, 'toto': 8}

Quotes (simple '' or double "") enclose character
strings. One can concatenate them using +.

For lists, tuples, strings, and dictionaries, the indexing
operator is written l[i]. For lists, tuples, and strings one
can also uses slices as l[:], l[:b], l[a:], or
l[a:b]. Negative indices start from the end.

The len() function returns the number of elements of a list, a
tuple, a set, a string, or a dictionary. One writes xinC to
tests whether x is in C.

Finally there is a special value called None to denote the
absence of a value.

In Python, there is no keyword for the beginning and the end of an
instructions block. Blocks are delimited solely by means of
indentation. Most of the time a new block is introduced by
:. Python has the following control structures:

In what follows, we deal with functions is the sense of
programming languages. Mathematical functions, as manipulated in
calculus, are handled by Sage in a different way. In particular it
doesn’t make sense to do mathematical manipulation such as
additions or derivations on Python functions.

One defines a function using the keyword def as:

def<name>(<argumentlist>):<instructionsequence>

The result of the function is given by the instruction
return. Very short functions can be created anonymously using
lambda (remark that there is no instruction return here):

A tuple is an immutable list. That is, it cannot be changed once
it is created. This can be useful for code safety and foremost because
it makes tuple hashable. To create a tuple, use parentheses instead
of brackets:

“Tuple-comprehensions” do not exist. Instead, the syntax produces
something called a generator. A generator allows you to process a
sequence of items one at a time. Each item is created when it is
needed, and then forgotten. This can be very efficient if we only need
to use each item once.

A dictionary is another built-in data type. Unlike lists, which are
indexed by a range of numbers starting at 0, dictionaries are indexed
by keys, which can be any immutable objects. Strings and numbers can
always be keys (because they are immutable). Dictionaries are
sometimes called “associative arrays” in other programming languages.

There are several ways to define dictionaries. One method is to use
braces, {}, with comma-separated entries given in the form
key:value:

We can iterate through the keys, or values, or both, of a
dictionary. Note that, internally, there is no sorting of keys
done. In general, the order of keys/values will depend on memory
locations can and will differ between different computers and / or
repeated runs on the same computer. However, Sage sort the dictionary
entries by key when printing the dictionary specifically to make the
docstrings more reproducible. However, the Python methods keys()
and values() do not sort for you. If you want your output to be
reproducable, then you have to sort it first just like in the examples
below:

Create a dictionary whose keys are the vertices of the above directed graph,
and whose values are the lists of the vertices that it points to. For
instance, the vertex 1 points to the vertices 2 and 3, so the dictionary will
look like:

Example: Construct a \(3 \times 3\) matrix whose \((i,j)\) entry is
the rational number \(\frac{i}{j}\). The integers generated by
range() are Python int’s. As a consequence, dividing
them does euclidean division (in Python2):