Installation

If you have a Mac or a Windows computer, the easiest way of getting Python together with all the most useful scientific libraries installed is to just install a Python Distribution. You can choose between:

Both of these are one-click installers containing Python and a collection of scientific libraries, including the Ipython Notebook that we use for the lecture.

If you are a Linux user, you may prefer to use the standard package manager to install the required packages. You will need at least python2.7, ipython-notebook, python-numpy, python-scipy, and python-matplotlib.


In [ ]:

Basics


The "hello world" program


In [ ]:
print "Hello World!"
  • Python provides both an interactive way to develop code and a way to execute scripts
  • What you do interactively is basically the same thing you (can) do in your scripts
  • Open an editor (gedit) an copy the previous line in a file. Save it with the name hello.py
  • Run it with:

      $ python hello.py

Calculator


In [ ]:
2 + 2

In [ ]:
4 - 2

In [ ]:
2.1 + 2

In [ ]:
3/2

In [ ]:
3.0/2.0

In [ ]:
2*3

In [ ]:
1+2j

In [ ]:
(3.0*10.0 - 25.0)/5.0

In [ ]:
3.085e18*1e6

Declaring variables


In [ ]:
t = 1.0  
a = 9.8 
s = 0.5*a*(t**2)
print s

In-place operators


In [ ]:
x = 1
x += 3
x

In [ ]:
x *= 5
x

Comparisons


In [ ]:
x1 = 10; x2 = 10

In [ ]:
x1 == x2

In [ ]:
x1 < 3

In [ ]:
x1 >= 10

In [ ]:
x3 = 12
x1 < 11 < x3

Strings


In [ ]:
x = "spam"
x

In [ ]:
print "hello\nworld!\tI said."

In [ ]:
"hello" == 'hello'

In [ ]:
"hello" < "hallo"

In [ ]:
"hello" > "bike"

In [ ]:
y = """Multiline string are
in triple quotes
      Indentation is preserved!
"""
print y

In [ ]:
s = "hello" ; e = "world"
print s + e

In [ ]:
s = 'hello'
len(s)

In [ ]:
s[0]

In [ ]:
s[-1]

In [ ]:
s[1:3]

In [ ]:
s[2:]

In [ ]:
x = float('3.2')
y = 4
y+x

In [ ]:
y + '3.2'

Lists

  • A ordered sequence of objects

In [ ]:
l = [1, 2, 3, 4]
l

In [ ]:
l = [1, "hello", "x", 1/3., 4 > 2]
l

In [ ]:
l[0]

In [ ]:
l[-2]

In [ ]:
l[1:3]

In [ ]:
l = range(11)
l

In [ ]:
l[0:8:2]

In [ ]:
l[::2]

In [ ]:
l[-4:2:-2]

In [ ]:
l[0] = "world"
l

In [ ]:
l.append(100)
l
  • Concatenate lists with + operator:

In [ ]:
l2 = ['x', 'y', 'z']
long_l = l + l2
long_l

In [ ]:
l = [10, 7, 9, 1, 5]
l.sort()
l

Dictionaries

  • A table that maps keys to values

In [ ]:
tel = {'John': 7192, 'Jim': 9871, 'Jan': 1253}
tel

In [ ]:
tel['John']

In [ ]:
tel['Marc'] = 2345
tel

In [ ]:
tel.keys()

In [ ]:
tel.values()

In [ ]:
tel.items()

In [ ]:
'John' in tel

In [ ]:
'Sam' in tel

Sets

  • An unordered collection of unique elements
  • In contrast to lists where finding an element takes O(n), look-up happens in O(1)
  • Like dictionaries but only with keys

In [ ]:
myset = set(['a', 333, 'b'])

In [ ]:
'a' in myset

In [ ]:
222 in myset

Logical flow control

  • if...elif...else
  • for ... in ...
  • while ...

If...elif...else


In [ ]:
if 2*2 == 5:
    print 'I know that!'
  • Blocks are delimited by indentation (4 spaces)

In [ ]:
if 2*2 == 4:
print 'I know that!'

In [ ]:
if 2*2 == 4:
    print 'I know that'
     print 'Wrong indentation'

In [ ]:
if 2*2 == 4:
    print 'I know that'
print 'This closes the block'

In [ ]:
x = -1
if x > 0:
    print "positive"
elif x == 0:
    print "zero"
else:
    print "negative"

In [ ]:
x, y = 10, 20
if x < 0 or y < 100:
    print "yes"
else:
    print "no"

In [ ]:
y = 20
x = y+2 if y < 10 else 100
print x

for ... in ...


In [ ]:
for i in range(10):
    print i

In [ ]:
for i in [0,1,2]:
    print i+2

In [ ]:
l = ['x', 10, {'Mark': 1012}]
for item in l:
    print item

In [ ]:
tel_book = {'Jan': 1253, 'Jim': 9871, 'John': 7192}
for name in tel_book:
    print name, 'telephone number is:', tel_book[name]

In [ ]:
for index, name in enumerate(tel_book):
    print index, name

In [ ]:
for index, obj in enumerate(l):
    print index, obj
  • For loop can be executed implicitly in list comprehensions:

In [ ]:
squares = [x**2 for x in range(10)]
squares

In [ ]:
squares = []
for i in range(10):
    value = i**2
    squares.append(value)

print squares

In [ ]:
squares = [x**2 for x in range(10) if x**3 < 50]
squares

In [ ]:
squares = []
for x in range(10):
    val = x**2
    if x**3 < 50:
        squares.append(val)

print squares

while ...


In [ ]:
# find all odd numbers whose square is smaller than 10000
# and whose cube is greater than 500
interesting_numbs = []
x = 0
while x**2 < 1e4:
    if (x % 2 != 0) and (x**3 > 500):
        interesting_numbs.append(x)
    x += 1

print interesting_numbs

In [ ]:
# throw random numbers until we get one smaller than 0.2
from random import random
counter = 0
while True:
    x = random()
    counter += 1
    if x < 0.04:
        break

print 'After', counter, 'trials, I got', x

Defining functions


In [ ]:
def double(x):
    """Return twice the input
    
    :param x: the value to be doubled
    
    :return: twice the amount of x
    
    """
    # maybe use + instead of * ?
    y = x*2
    return y

In [ ]:
z = double(10)
print z

In [ ]:
double('hello world!')

In [ ]:
double(2+1j)

In [ ]:
double()

In [ ]:
def double_improved(x, method='*'):
    """Return twice the input.
       
    :param x: the value to be doubled
    
    :param method: 
    
        *optional* argument specifying  
        the method to double `x`
    
    :return: twice the amount of x
    
    :raises: 
    
        ValueError in case the chosen method is not supported
    
    """
    print 'Doubling using', method
    if method == '*':
        return x*2
    elif method == '+':
        return x+x
    else:
        raise ValueError('Method '+method+' not known!')

In [ ]:
double_improved(2)

In [ ]:
double_improved(3, method='+')

In [ ]:
double_improved('x')

In [ ]:
double_improved(10, '*')

In [ ]:
double_improved(1, '/')

In [ ]:
double({'a':1})
  • functions are objects like all others: you can pass functions as arguments to other functions!

In [ ]:
def multiply(x, y):
    """Mutiply x by y"""
    return x*y

def double_generic(x, method=multiply):
    """Return twice the input.
       
    :param x: the value to be doubled
    
    :param method: 
    
        *optional* argument, the actual function
        that is applied to `x`
    
    :return: twice the amount of x
    
    """
    print 'Doubling using', method
    return method(x, 2)

In [ ]:
double_generic(10)

In [ ]:
def donothing(x, y):
    """This function is useless"""
    return x

In [ ]:
double_generic(10, method=donothing)
  • the string after definition is the help text of your function

In [ ]:
help(double_generic)

In [ ]:
help(enumerate)

In [ ]:
double_generic?
  • Methods are functions attached to objects

In [ ]:
l = [3, 1, 2]
l.sort()
l

In [ ]:
"hello world".split()

In [ ]:
for num, word in enumerate("hello world. I am here".split()):
    print "Word number",num, ':', word

Introspection

  • by hitting TAB you can inspect the methods of any object

In [ ]:
s = "hello world" # hitting TAB will show:
s.capitalize  s.format      s.isupper     s.rindex      s.strip
s.center      s.index       s.join        s.rjust       s.swapcase
s.count       s.isalnum     s.ljust       s.rpartition  s.title
s.decode      s.isalpha     s.lower       s.rsplit      s.translate
s.encode      s.isdigit     s.lstrip      s.rstrip      s.upper
s.endswith    s.islower     s.partition   s.split       s.zfill
s.expandtabs  s.isspace     s.replace     s.splitlines  
s.find        s.istitle     s.rfind       s.startswith  

In [ ]:
help(s.replace)

In [ ]:
s = "hello world"
s.replace("hello", "go away")

Scripts & Modules

  • Let us first write a script, that is a file with a sequence of instructions that are executed each time the script is called.

    The extension for Python files is .py. Write or copy-and-paste the following lines in a file called weather.py


In [ ]:
things = 'day, weather, life'
qualities = ['bad', 'really bad', 'terrible']
for thing in things.split(','):
    for quality in qualities:
        print 'This', thing.strip(), 'is', quality

message_in_the_bottle = "Euthanasia!"
print "You want:", message_in_the_bottle
  • You can execute the script interactively in ipython by running

      %run weather.py
    
    

    The local variables are available


In [ ]:
%run weather.py

In [ ]:
message_in_the_bottle
  • ...or you can execute the script as a standalone program by running in a terminal

      $python test.py
  • Create your own collection of functions: a module

  • Put the following functions in test.py


In [ ]:
def scream(x):
    return x.upper()

def whisper(x):
    return x.lower()

In [ ]:
import test
print test.scream('Is there anybody here?')
print test.whisper('I LIKE CAPS!')

I/O: Read & Write Files


In [ ]:
fh = open('lorem.txt', 'r')

In [ ]:
for line in fh:
    print line[:10], '...',
    words = line.split()
    print len(words)
  • after iterating on the lines, we are located at the end of file:

In [ ]:
for line in fh:
    print "Still more lines!"
else:
    print "No lines!"

In [ ]:
# rewind
fh.seek(0)
count = 0
for line in enumerate(fh):
    count += 1
print count

In [ ]:
fh.close()

In [ ]:
fhw = open("tobewritten.txt", 'w+')

In [ ]:
for i in range(10):
    fhw.write(str(i)+"\n")
fhw.flush()

In [ ]:
fhw.seek(0)
content = fhw.read()

In [ ]:
content

In [ ]:
content.splitlines()

In [ ]:
fhw.seek(0)
content = fhw.read()
lines = content.splitlines()
int_list = [int(i) for i in lines]
print int_list

In [ ]:
fhw.close()

Standard Library

The Batteries included!

  • from a web server: SimpleHTTPServer ... to converting between color systems: colorsys
  • from profiling: cProfile ... to secure hash and digest algorithms hashlib
  • from threads: threading to subprocesses: subprocess
  • Go and see yourself the list of modules in the Standard Library: http://docs.python.org/py-modindex.html

pickle: The one battery you will need for sure – Python object serialization.


In [ ]:
import pickle

In [ ]:
l = [1, 2, 3]

In [ ]:
dumpfile = open('dump.pic', 'w')

In [ ]:
pickle.dump(l, dumpfile, protocol=-1)

In [ ]:
dumpfile.close()

In [ ]:
dumpfile = open('dump.pic', 'r')

In [ ]:
x = pickle.load(dumpfile)

In [ ]:
print x

Debugging


In [ ]:
def print_fourth_element(mylist):
    print 'The forth element is:'
    print mylist[3]


def main():
    a = 42
    b = 'lorem ipsum'
    c = 4+4j

    mylist = [a,b,c]
    print_fourth_element(mylist)

main()

In [ ]:
%debug

In [ ]:
import pdb

def lets_debug_this(idx):
    pdb.set_trace()
    print ('I am in iteration %d' % idx)

for irun in range(4):
    lets_debug_this(irun)

Python is great for Object Oriented Programming (but out of the scope of this tutorial)


In [ ]:
class MyClass(object):
    def __init__(self, name='Custom Class'):
        self.name = name
    
    def print_name(self):
        print 'My name is ' + self.name
        
myobject = MyClass('Example Object')
myobject.print_name()

In [ ]:
import this

In [ ]: