Sage Reference: A Python Primer
About Python
Python is a high-level programming language that is designed to be easier and faster to work with than some earlier languages, such as C or Java. Some notable facts about Python:
- Python first appeared in 1991, and was designed by Guido van Rossum. It is developed under an open source license, so it’s free to use and distribute (even commercially).
- Python is been ranked within the top eight most popular programming languages for over 7 years. Many government organizations and companies use Python extensively, such as NASA, CERN, and Google. It’s also widely used in the scientific community.
- Object-oriented and structured programming are fully supported in Python. Many other paradigms are supported via extensions.
- The developers of Python intended for it to be fun to learn and use. The name is taken from Monty Python, and frequent references to the comedy group can be found in the documentation.
- Readability is important. Indented lines within functions, loops, and other statements are not simply good practice but are actually required. On the other hand, you do not need to include any symbols that indicate the end of a line or block of code - only whitespace is needed.
- There are many additional libraries, extensions, and shells that you may want to investigate if you’re interested in Python. Many of these can be identified by the inclusion of the “Py” prefix in their name, such as NumPy or PyPy. There are also compilers available to compile Python to other high-level languages (and vice-versa).
Syntax and Comments
Because Sage is based on Python, it uses the same syntax, which relies heaving on whitespace (instead of surrounding code blocks with braces). Code blocks must be indented to be interpreted correctly. Usually, not doing so returns an error:
Other times, forgetting to indent may not trigger a Python error, but will lead us to the wrong result. Suppose wish to print the value of sin(x) and cos(x) for integer values of x between 1 and 5, and we create the following code:
There are a few issues here. One, we likely wanted the decimal value of sin(1), and we'll see how to correct this problem soon. We also notice our loop only "went up" to 4, not 5; this is due to the way Python interprets intervals (all are half-closed, inclusive of the lower limit but excluding the upper limit). Finally, while sin(x) was printed for \(x = 1,2,3,4\), only cos(4) printed. This is because that line was not indented below the for loop, so it was not considered part of the loop. To correct all three problems:
To include a comment (a piece of writing in your code you do not want executed), use the # symbol:
Conditionals
Sage uses the symbols
==
,
<
,
>
,
<=
,
>=
, and
!=
to compare two expressions. The result of each comparison is either True or False:
Note the "double" equal sign used here, as opposed to the single equal sign used to assign a value.
Two statements can be combined with
or
and
and
. Two statements connected with "or" will return True if either statement is true, while statements joined with "and" will be true only if both statements are true:
Variables and Data Types
Python allows any value to be assigned to a variable, without declaring a variable type.
Shorthand for multiple assignments:
Strings
Strings can be surrounded with either double quotation marks (") or single ('). Whichever symbol is used, the other symbol is interpreted as part of the string itself, so you can create strings with apostrophes. We can also get the character at position x in a string, but note that the count (index) begins at 0.
Lists
A list is an
ordered set of elements, surrounded by square brackets. Lists can contain numbers, strings, and even other lists. Lists are zero-based, which means the first element of the list has index 0. In a list containing 10 objects, the last would have index 9. You can also refer to list elements with negative indices, where the last object has index -1:
Elements in nested lists are referenced using additional brackets. There's an index for each 'level':
A "slice" of a list can be defined by specifying two indices. The new list returned contains all elements of the list, in order, starting with the first index up to (but not including) the second:
To add a new element to the end of a list, use
append
:
If you need to place a new element in a particular location of the list, use
insert
and provide the index of the first element to be "bumped" to the right:
Concatenating lists can be done using the
extend
command:
You can create a list with repeated elements using *:
The
remove
command removes the first instance of an element from a list:
The
pop
command removes the last element in a list, and returns it. After evaluating the following, print the current list L:
Tuples
Tuples are also ordered sequences, but unlike lists, tuples are not mutable. This means we cannot change the value of an entry after the tuple is defined. Tuples are less flexible, but more secure for data that you do not want lost, and are faster to work with than lists because they are not dynamic (take Programming I for more on this):
You can use
in
to check if an element is in a tuple, but you cannot add or remove elements, or concatenate tuples.
Sets
Sets are collections with no order. We cannot retrieve the item at position 2, for instance, because the concept of position does not apply. However, we can use operations like union and intersection. Also, note that like mathematical sets, Python sets only 'count' each object once.
Dictionaries
Dictionaries are useful when working with a lot of data, and are optimized for retrieving a value by key.
If Statements
We can use conditionals and if-else statements to execute certain code when a particular condition is true. Try changing the value of \(x\) below and re-evaluating:
Note the indentation - this is important. A code block that should be executed in a particular instance is denoted only by whitespace, instead of braces or other indicators used by many other programming languages. The code below includes two lines to be run if \(x\) is greater than three, and will do nothing otherwise.
Python does not have an "else if" method; instead, use nested if statements:
For Loops
When you need a certain process to run a particular number of times, you can use a for loop. The sample below prints 2 times every number between 0 and 4. The total number of loops is 5, as specified as the range parameter.
Again, indentation is required. You can include multiple lines of code to run for each loop:
If you’d rather define a loop to start at a value other than 0, you can specify the start and end values. Note that in the example below, the first value in the range is used in the calculation (3*2 = 6 is printed) but the last is not - there are still only 2 loops.
You can also loop over the elements of a list or set:
While Loops
While loops are used to repeat a process as long as a particular condition is true:
Note that part of the loop changes the value of \(x\), which is being used in the test condition. Without changing the value of \(x\), the condition would always be true, and the loop would never end. As soon as \(x\) reaches a value of 5, the loop ends, since 4*5 = 20 is not less than 20.