A quick introduction to Python
Sage is based on the python programming language. This demo is introduction to the basics of the python language.
Variables and simple types
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.
Some simple types of Python: bool, str, int.
By default, integers are not int but Sage Integers.
Other python types
standard types also contain list, tuple, set, dict.
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:
You can access and modify elements of the list.
You can extend a list or concatenate it with another list.
some other operations:
A tuple is very similar to a list, it is constructed using parentheses and cannot be changed after its creation, it is immutable.
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, only immutable elements can be hashable.
A dictionary is an association table, which associate values to keys. Keys must be hashable. One creates dictionaries using the constructor dict, or using the syntax:
You can iterate either on keys, values or both.
Controle structures
In Python, there is no keyword for the beginning and the end of an instructions block. Blocks are delimited thanks to indentation. Most of the time a new block is introduced by :. Python has the following control structures:
- Conditional instruction:
- Iterative instructions
Functions
In what follows, we deal with functions in the sense of programming languages. Mathematical functions 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.
Functions are first class objects like any other. For example, they can be passed in as arguments to other functions.
Python is object oriented: some functions are methods in objects.
You can give default values for arguments in functions:
You can return multiple things from a function:
Exercise: Create the list [63, 12, -10, \text{``a''}, 12], assign it to the variable L, and print the list.
Exercise: Create the empty list (you will often need to do this).
Creating Lists II: range¶
The range function provides an easy way to construct a list of integers. Here is the documentation of the range function:
range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
Exercise: Use range to construct the list [1,2,\ldots,50].
Exercise: Use range to construct the list of even numbers between 1 and 100 (including 100).
Exercise: The step argument for the range command can be negative. Use range to construct the list [10, 7, 4, 1, -2].
The range function returns python int, they are different from Sage Integer. The srange function is an equivalent of the range function that returns Sage Integers.
Exercise: look at the different outputs below then create a list of all Integer factorizations for 0<n<100.
Creating Lists III: list comprehensions¶
List comprehensions provide a concise way to create lists from other lists (or other data types).
Example We already know how to create the list [1, 2, \dots, 16]:
Using a list comprehension, we can now create the list [1^2, 2^2, 3^2, \dots, 16^2] as follows:
Exercise: [Project Euler, Problem 6]
The sum of the squares of the first ten natural numbers is
The square of the sum of the first ten natural numbers is
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Filtering lists with a list comprehension¶
A list can be filtered using a list comprehension.
Example: To create a list of the squares of the prime numbers between 1 and 100, we use a list comprehension as follows.
Exercise: Use a list comprehension to list all the natural numbers below 20 that are multiples of 3 or 5. Hint:
- To get the remainder of 7 divided by 3 use 7%3.
- To test for equality use two equal signs (==); for example, 3 == 7.
Project Euler, Problem 1: Find the sum of all the multiples of 3 or 5 below 1000.
Exercise:
A Pythagorean triple is a triple (x,y,z) of positive integers satisfying x^2+y^2=z^2. The Pythagorean triples whose components are at most 10 are:
Using a filtered list comprehension, construct the list of Pythagorean triples whose components are at most 50.
Project Euler, Problem 9: There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
Slicing Lists¶
You can slice a list using the syntax L[start : stop : step]. This will return a sublist of L.
Exercise: Below are some examples of slicing lists. Try to guess what the output will be before evaluating the cell.
Advanced exercise: The following function combines a loop with the some of the list operations above. What does the function do?
Using sets and dictionaries
Exercise: create the set of letters different than 'b' contained in the string "abracadabra"
Exercise: The method a.factor() when a is an Integer gives an object that represents the prime factors of a. It can be converted to a list or a dictionary. Test the methods below then create a dictionary that associate with a natural number n<100, the number of different prime factors of n.
Note: be carreful, the range function returns python int and not Sage Integer, you can compute the factor method only on Sage Integer, use the srange function instead.
Functions
Exercises:
- Write a function is_even returning True if n is even and False otherwise.
- Write a function every_other which takes a list l and returns a list containing every other element of l
- Write a function computing the n-th Fibonacci number. Try to improve performance.