Using python

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]:
2

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]:
9.5

These are the most basic operation and there are several more. We wont bother about them in this text though.

Variables

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]:
8

We can write


In [90]:
a + 3


Out[90]:
8

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]:
5.7

Without variables this would get messy and very, very soon extremely difficult.

Objects

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

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]:
2

Often, this is not what you wanted. This leads us to the next object.

Floats

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]:
2.4

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.

Lists and tuples

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]:
[1, 3.5, [3, 5, []], 'this is a string']

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]:
[3, 5, []]

In [102]:
a[2][1] # We can access an objects in a list which is in a list


Out[102]:
5

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]:
19.2

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]:
[1, 13.2]

In [114]:
a[0:2] + a[0:2] # You can put two lists together with addition.


Out[114]:
[1, 13.2, 1, 13.2]

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]:
['bleen', [2, 4.1, 'grue'], 4.3]

In [138]:
del a[-1] # We can also index from the end of the list. -1 indicates the last element
a


Out[138]:
['bleen', [2, 4.1, 'grue']]

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]:
(2, 'e', (3.4, 6.8))

In [147]:
a[0]


Out[147]:
2

In [149]:
a[-1][-1]


Out[149]:
6.8

In [150]:
a[1] = 0


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-150-7e9f8b12e919> in <module>()
----> 1 a[1] = 0

TypeError: 'tuple' object does not support item assignment

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

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]:
'here is a string'

In [154]:
a = "Here's another" # Notice that we included a single quote in the string.
a


Out[154]:
"Here's another"

In [164]:
a = """
This string
spans
several lines.
"""
a # \n means new line. They can be manually included with \n.


Out[164]:
'\nThis string\nspans\nseveral lines.\n'

In [166]:
print a # To see \n as an actual new line we need to use print a.


This string
spans
several lines.

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]:
'The sum of [1, 2, 3, 4, 5] is 15'

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)


Help on built-in function sum in module __builtin__:

sum(...)
    sum(sequence[, start]) -> value
    
    Return the sum of a sequence of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the sequence is
    empty, return start.