Programming with Python

Some things to know before you start with Python:


Python can be used to execute (python-) programs, but for development a far more interesting tool is ipython, which lets you develop your code interactively, step by step.

Installing ipython in Linux is done with the package management of your distro. In OSX the easiest way is to use pip. If this is not already on your system, download this script:

then in the UNIX terminal: go to the location where you saved and type

sudo python

Now you can use pip to install other stuff like ipython and other python modules:

pip install ipython
... and other modules that are not already present on your system, e.g.
pip install numpy


In Python, a line of comment starts with a '#'. Multi-line comments are enclosed by """ and """.


Python scripts use levels of indenting to create functional blocks. Compare this piece of C++ with a similar piece of Python:
if(x > 5){
  cout << "x exceeds 5" << endl;

In C++ you use { and }. Indenting in C++ is optional but strongly advised because of readability. However, the compiler doesn't use it.

In Python the compiler actually uses the indent level, so it's not just a visual issue but very functional. In this example you shift the code some spaces or tabs to the right to bind it with the 'if'

if x > 5 :
  print "x exceeds 5"
Also note the : at the end of the if-line.


Functions are defined with the def keyword. The function body is indented to the right, like we discussed under Indenting. More about this in the chapter about functions.
def surface(w,h):
  # calculate w*h and return it to the caller
  s = w*h
  return s

print surface(4,5)
Again, note the : at the end of the function-line and note that the comment line needs to have the same indent level as its surrounding code.


Python relies heavily on the use of external libraries. There are many and they are very useful. To import a library or parts of it, we use the import keyword. We can choose to use an alias, i.e. a local name.

import numpy as np
where np is the alias that we can use throughout our program. Now we can call any function in the numpy library as np. like this:
import numpy as np

np.zeros(10) # create array with all values set to zero