Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Image: ubuntu2004
Introduction
Camilo Garcia Trillos - 2020
In this notebook
In this notebook we will deal mainly with syntax and semantics in Python
we explore some basic expressions in Python
we introduce some types
we introduce some of the most important control flow statements
Jupyter Notebooks
This is a Jupyter notebook. It is an interface allowing us to combine code (in this case Python) and formatted text in a unified way.
The basic unit in a notebook is a cell. You are right now reading the content of a "Markdown" cell, designed to input formatted text. There are also 'Code' cells, designed to input executable code.
You can add a new cell by clicking on the + button on the lower toolbar. Alternatively, press A (for inserting a cell above or B for inserting a cell below).
Click on the cell to start editing it. Alternatively, you can move between cells with your arrows (note the blue highlighter on the right), and click Enter to edit one cell.
To change the type of cell (from 'code' to 'markdown', use the choice tab on toolbar while on the cell.
To run the code on a cell (or to format the text you input) you can either click on the 'play' button on the lower toolbar, or hit Ctrl+Enter
You can also cut, paste and move cells. Hover your mouse over the buttons on the lower toolbar to know more.
To familiarise yourself with the interface:
On the upper toolbar, click on Help> User Interface tour, and follow the instructions to get an overview of this interface.
For more information on the Python notebook in general, click on Help> Notebook help
To know more about the keyboard shortcuts, go to Help> Keyboard shortcuts
Short Exercise: Add a cell, write '1+1' and execute this program. Then, select the cell again and change its type to Markdown You can finally delete this cell.
The above line has a statement that asks Python to execute the method/function print receives a 'string' and then shows the string as an output. Strings in Python can be denoted by either double or single quotations. To verify this, let us ask Python to compare if a string with single quotations is the same as a string with double quotations.
The comparison operator is ==
The output of this comparison is True, which means that the two values are the same. Let me remark that in general Python compares 'values' and not 'references'. This is an important distinction from other programming languages.
The operator =, with a single equal, is used to make an assignment:
Above we are creating an object that is initialised to contain a string. There is no need to declare the type of the object message. It will be then treated as a string, which is why the function print works.
Note in passing that we can make comments on a code cell by preceding the comment by #
Python is an object-oriented programming language. Objects of a given type or class have associated a certain number of methods that act on them. Take for example the following code
The method upper is available for string objects and turns every character in their uppercase version. Here is another one
Note that we did not need to use print above. By default the result of the last command of a cell that returns a value is displayed. Let us finally remark that we can use the triple quotes to write text in several lines.
Compare the versions with and without print.
The operation is performed using 'floats', that is numerical representation of real numbers. Digital computers have only a finite number of digits to represent a real, and so there are roundup errors. The above code shows that operations that for us are simple to do 'without roundup' must be done only approximately by a computer.
We can also have operations with complex numbers. In Python, the imaginary number is denoted by j
The above operation is executed in the complex numbers (or more appropriately the float version of the complex numbers). The precedence in executing the operations follows the usual convention: first, parentheiss are solved from inner to outer ones, then, for common mathematical operators de precedence is: power, then division and multiplication, then sum and substraction.
Also, note the function 'type': it returns the type of a given object. While we are at it, let us check the name of other types we have encountered before
Division is a bit special. Observe the result of the following operations:
Indeed, the double slash / signals integer division. Note that we can use it also with float numbers
The modulo operator, that allow us to obtain the residual of a division, is also included:
Powers are defined using the operator double star '**'
Short exercise: Remark the difference between the two instructions above. What can you say?
Main structured types
Python comes pre-loaded with some structured types to keep collections of objects. The main ones are: List, tuple, dictionary, set
It is very important to learn about the features of each one of these structured types, as many errors in programming come from misunderstanding them
Any element on a list can be accessed trough the square bracket operator. The indexation on the vector starts from zero
As shown above, we can provide negative numbers to the position. It simply access the position as counted from the end. Try with some other positions until you are sure how it works.
It is also possible to get slices of a vector, by using [m,n]: this returns all elements in the vector starting from position m and ending in position n-1
In the above, if no number is entered, the corresponding extreme is implicitly understood. Take a look at these examples:
Slices can also be used to run over the elements of a list in inverse order, or following a sequence
Lists can also be extended.
List assignments are passed by reference. This means that when we assign them to another variable, we only copy an adress to access them in memory. Here is an example
Hence, despite the name, another_list points to the same list. However, lists are compared by value, as seen in this example:
Lists can be concatenated with the operator +
Note in particular that this does not add up elements in a list. In particular, we cannot concatenate an integer to a list.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-66e780646bd1> in <module>
----> 1 list1+1 # This command generates an error
TypeError: can only concatenate list (not "int") to list
But we can do as follows
Also, note that concatenation does not modify the original list but creates a new one: i.e., the original list does not change.
The * operator repeats a list formation
We can also have lists of lists (but they are not matrices!) and lists with different types and lengths
We end up our overview of lists by looking at some of the methods associated with it. The best method to discover them is to write a list and put a dot and the end and click TAB (might not work depending on your browser and OS)
Some of the more relevant are shown below
Some methods are different and specific of strings
A set is a structure where elements are unique. They are created with curly braces { }
We can add elements, remove elements, and perform mathematical operations like union, intersection, symmetric difference.
Note that sets do not have indices, so the following code does not make sense
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-45-c61df569ed49> in <module>
----> 1 set1[1] # this generates an error
TypeError: 'set' object is not subscriptable
A tuple can be created using round braces.
Tuples are similar to a list except that elements cannot be changed once created: they are an example of an immutable structure
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-96b0480c90ed> in <module>
----> 1 tuple1[1]=3 #this generates an error ... tuples are immutable
TypeError: 'tuple' object does not support item assignment
Finally, a dictionary is a structure to connect keys and outputs. It is defined also using the curly braces { }, but instead of simply listing the elements, we list couples of the form key:value. Keys can be any other immutable object (like numbers and basic strings).
The key element is a generalisation of an index. Here are some examples:
Here are some examples of methods for dictionaries
Basic control flow statements
To close this notebook, we will look at the essential control flow statements (i.e. commands to determine the flow of a program) in Python. The main ones are:
Conditionals: if (condition): --- elif(condition): --- else:---
Conditional loops: while (condition): --- else:---
Automatic loops: *for (iterative): ---
The structure is determined by indentation
Let us look at some examples: you are encouraged to change the inputs and modify the code until you undertstand how the flow of commands works.
In the above code, the code indented after if is run only when the condition is satisfied. The code indented after elif is run only if a>b. The code indented after elif is run only if a>b is not satsified (i.e. a<=b) and b>a. Finally the code after else is run only if neither of the conditions is satsified (i.e. when a==b)
We can modify the above example to act on the first n natural numbers. To do this, we introduce the command range
In general, range can generate a pattern from a given start, to a given end with certain step: range(start,end,step). If step is not given, step=1.
Here is a version of the same code using while and avoiding range.
Here is our last example combining many of the elements we introduced before. It prints the primes less or equal to a given number using a cribe algorithm. Take it as an exercise to find out how (and why) it works. You might need some time to understand it, but don't get discouraged by this
Write a code that, for a given tuple , returns the roots (possibly complex) of the equation
Note: if there is a double root, only one number must be returned.
Starting from two integers, , and an initial value integer , generate values of a sequence
Note: this is one of the earliest forms of pseudo-randon number generators. See for example this wikipedia article