Programming with Python

Some things to know before you start with Python:

ipython

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:

get-pip.py

then in the UNIX terminal: go to the location where you saved get-pip.py and type

sudo python get-pip.py

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

Comment

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

Indenting

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;
  break;
}

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"
  break
Also note the : at the end of the if-line.

Functions

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.

Libraries

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.

Example:
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