Python overview

= A basic overview =

Theory
On Python:
 * Indentation = blocking
 * Runtime evaluation
 * dynamic typing
 * everything is a class
 * multi-paradigm
 * batteries included
 * garbage collector
 * a bit of interfacing
 * Everything is a references, deepcopy

Executing a script
File helloworld.py  print "hello world"  Execute by typing  python helloworld.py 

Function definition
A simple function can is defined as:  def multiply(a, b): return a*b  Arguments with default values can be added like this:  def log(x, base=2.71828183) return math.log(x)/math.log(base) 

Importing a module
Modules are included using the import statement. Most of the power of Python is stored in modules. The math module contains e.g. all math functions. Modules can not only contain function definitions and class definitions, but also variables. Example:  import math print "The square root of 4 is", math.sqrt(4) print "Pi =", math.pi math.pi=4 print "In engineering, pi is sometimes", math.pi  This is different to other programming languages and has to be handled with care: Modifying the state of a module can lead to undesired consequences.

Modules can be imported into the local namespace, but this is dangerous (see the pi example above):  from sys import * print argv  Sometimes it is convenient to import Modules with a local name that is different from the module's real name. Frequently this is found for the module numpy:  import numpy as np. x=np.linspace(0,1,101) </tt> This reduces the amount of typing and makes it possible to use different versions of the module without changing the code.

Conditional
Conditionals are straightforward:  if a==b: print "a and b are equal" else: print "a and b are different" </tt>

Lists
In Python no formal difference between a list and an array is made. Lists can contain anything. A list can be created using brackets []</tt>. Example  mylist = [ 1, 2, 3] mylist.append(3.5) </tt> Tuples are a similar datatype, created with round brackets </tt>, but its elements can not be changed.

Dictionaries
Python dictionaries are known as associative arrays, or maps in other languages, or can be considered a set of keys and values. Keys can not only be strings, but any <it> hashable </it> object, for that has a cmp</tt> function. Example:  d = {} d["Paris"]="Eiffel Tower" d["London"]="Big Ben" for k in d.keys: print k, "you find famous", d[k], "." </tt>

Loops
Loops are very intuitive in Python. The for-loop is similar to the tcl</tt> foreach loop. Example:  for i in [0,1,2,3,4]: print i </tt> Lists with integers can be created using the range function:  for i in range(5): print i </tt> While loops are easy as well:  i=5 while i>0: print i   i-=1 </tt>