Python is an interpreted language. This means that there is a "python program" that reads your input and excecutes it. If you open your ipython interpreter, you'll see the following message (or something very similar):
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Type "copyright", "credits" or "license" for more information.
IPython 3.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
where In [1]: is a command prompt. Whenever I write
In [86]:
1 + 1
Out[86]:
I mean that the command is written in the ipython command prompt (or in the ipython notebook if you prefer to use that). There are some lines above the command prompt. These are information on the current python and ipython version and tips on how to get help. But first, let us look at some of the basic operations, addition, subtraction, multiplication, division and exponentiation. In python, these would have the symbols +, -, *, / and **. If we would like to calculate \begin{align} \frac{3.6\cdot 5 + (3 - 2)^{3}}{2} \end{align} we would write
In [92]:
(3.6*5 + (3 - 2)**3)/2
Out[92]:
These are the most basic operation and there are several more. We wont bother about them in this text though.
Python, as most programming languages relies on the fact that you can create something called a variable in it. This is similar to what in mathematics is called a variable and a constant. For example, we can define a variable with the name $a$ in python and let it have the value $5$ by typing
In [87]:
a = 5
Python now knows that there is such a thing as $a$ which you can use to do further operations. For example, instead of writing
In [89]:
5 + 3
Out[89]:
We can write
In [90]:
a + 3
Out[90]:
and we get the same result. This might seem as it is not that useful, but we can use it the same way as we use constants and variables in mathematics to shorten what we have to write. For example, we may want to calculate averages of averages.
In [91]:
b = (2.5 + 6.3)/2
c = (5.3 + 8.7)/2
(b + c)/2
Out[91]:
Without variables this would get messy and very, very soon extremely difficult.
Just as there are different kind of objects in mathematics such as integers, reals and matrices, there are different kind of objects in python. The basic ones are integers, floats, lists, tuples and strings which will be introduced here.
Integers behave very much like the integers in mathematics. Any operation between two integers will result in an integer, for example $5 + 2$ will result in $7$, which is an integer. Notice though that division might not always lead to a new integer, for example $\frac{5}{2}$ is not an integer. In python operations between integers always results in a new integer. Because of this, division between integers in python will drop the remainder.
In [97]:
a = 12
a / 5
Out[97]:
Often, this is not what you wanted. This leads us to the next object.
A float, or a floating point number, works very much like a real number in mathematics. The set of floats is closed under all the operations we have introduced just as the reals are. To declare a float we simply have to add a dot to the number we wish to have, like this
In [98]:
a = 12.
and now, $a$ is a float instead of am integer. If we do the same operation as before, but with floats we get
In [99]:
a / 5.
Out[99]:
Now it seems as if we only should use floats and not use integers at all because of this property. But as we will se soon the integers will play a central role in loops.
Just as integers and floats are similar, so are lists and tuples. We will begin with lists. A list is an ordered collection of objects. The objects can be of any type, it can even contain itself! (But that is usually not very useful). A list is initiated with matching square brackets [ and ].
In [100]:
a = [1, 3.5, [3, 5, []], 'this is a string']
a
Out[100]:
Because a list is ordered, the objects in the list can be accessed by stating at which place they are. To access an object in the list we use the square brackets again. In python (and most otehr programming languages) counts from $0$, which means that the first object in the list has index $0$, the second has index $1$ and so on. So to access an object in a list we simply type
In [101]:
a[2] # Accessing the third element in the list. (This is acomment and is ignored by the interpreter.)
Out[101]:
In [102]:
a[2][1] # We can access an objects in a list which is in a list
Out[102]:
In [111]:
a[1] = 13.2 # We can change values of the objects in the list
In [112]:
a[0] + a[1] + a[2][1]
Out[112]:
You can also access parts of a list like this:
In [113]:
a[0:2] # Return a list containing the first element up to but not including the third (index 2) element
Out[113]:
In [114]:
a[0:2] + a[0:2] # You can put two lists together with addition.
Out[114]:
The lengt hof a list is not fixed in python and objects can be added and removed. To do this we will use append and del.
In [136]:
a = [] # Creating an empty list
a
Out[136]:
In [137]:
a.append('bleen')
a.append([2,4.1,'grue'])
a.append(4.3)
a
Out[137]:
In [138]:
del a[-1] # We can also index from the end of the list. -1 indicates the last element
a
Out[138]:
Tuples are initialized similarly as lists and they can contain most objects the list can contain. The main difference is that the tuple does not support item assignment. What this means is that when the tuple is created its objects can not change later. Tuples are initiated with matching parentheses ( and ).
In [146]:
a = (2, 'e', (3.4, 6.8))
a
Out[146]:
In [147]:
a[0]
Out[147]:
In [149]:
a[-1][-1]
Out[149]:
In [150]:
a[1] = 0
Because tuples does not support item assignment, you cannot use append or del with it. Tuples ar good to use if you want to make sure that certain values stay unchanged in a program, for example a group of physical constants.
Strings are lines of text or symbols and are initiated with doubble or single quotes. If you wish for the string to span several lines you can use triple double quotes
In [152]:
a = 'here is a string'
a
Out[152]:
In [154]:
a = "Here's another" # Notice that we included a single quote in the string.
a
Out[154]:
In [164]:
a = """
This string
spans
several lines.
"""
a # \n means new line. They can be manually included with \n.
Out[164]:
In [166]:
print a # To see \n as an actual new line we need to use print a.
Here, you saw the first occurrence of the print statement. It's functionality is much greater than prettifying string output as it can print text to the command or terminal window. One omportant functionality of the string is the format function. This function lets us create a string without knowing what it will contain beforehand.
In [171]:
a = [1,2,3,4,5]
In [172]:
str = "The sum of {} is {}".format(a, sum(a))
str
Out[172]:
It uses curly brackets { and } as placeholders for the objects in the format part. There are many other things you can do with strings, to find out use the question mark, ?, in the interpreter after the variable you want more information about. Notice that this does not work in the regular python interpreter, you have to use ipython. You can also use the help function to get help about functions and variables. It works both in the regular interpreter and in ipython.
In [178]:
a?
In [179]:
help(sum)