Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Python

Tutorial

Michael Muenzer

Graz University of Technology

March 18, 2013


Slides based on previous work by Jan Pöschko and Klaus Potzmader
Introduction Language basics Advanced concepts Special modules

Why Python?

Python is:
• very readable
• easy to learn
• interpreted & interactive – like a UNIX shell, only better
• object-oriented – but not religious about it
• slower than C, but it is easy to integrate C, Fortran, Java

“Batteries included”

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

The Zen of Python


• Beautiful is better than ugly.
• Explicit is better than implicit.
• Simple is better than complex.
• Complex is better than complicated.
• Flat is better than nested.
• Sparse is better than dense.
• Readability counts.
• Special cases aren’t special enough to break the rules.
• Although practicality beats purity.
• Errors should never pass silently.
• Unless explicitly silenced.
• In the face of ambiguity, refuse the temptation to guess.
• There should be one – and preferably only one – obvious way to do it.
• Although that way may not be obvious at first unless you’re Dutch.
• Now is better than never.
• Although never is often better than right now.
• If the implementation is hard to explain, it’s a bad idea.
• If the implementation is easy to explain, it may be a good idea.
• Namespaces are one honking great idea – let’s do more of those!

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Installing Python

• Included in most distributions of Linux and Mac OS X


• Downloadable from http://www.python.org/download/
• Libraries:
• NumPy: http://sourceforge.net/projects/numpy/
• matplotlib: http://sourceforge.net/projects/
matplotlib/files/matplotlib/
• NetworkX: http://networkx.lanl.gov/install.html
• Editors:
• Eclipse
• emacs, vim
• . . . (anything that knows how to handle tabs and spaces)

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Invoking Python

• Interactive mode: Open a console/terminal window and run


python (fancier alternative: ipython)

• Execution: python myfile.py or execfile(’myfile.py’)


• Make sure you have python 2.7.3 installed as it’s the version
used in our tests

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Language basics

n = 42 # integer
x = 3.14159 # float
x = ” Hello world ! ” # s t r i n g

• No variable declarations
• Dynamically typed

String delimeters:
s = ” Hello world ! ”
s = ’ Hello world ! ’
s = ””” H e l l o
w o r l d ! ””” # multi −l i n e s t r i n g

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Booleans

• True is true, False is false


• 0, "" and None are false, (almost) everything else is true

not A
A and B
A or B
Comparisons: ==, !=, <, <=, >, >=
2 == 2
1 < 2 <= 3
1 == 2 and ”3” or ” 4 ” # = ”4”

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Lists

L = [1 , 2 , 3]
L[0] # = 1
L[1:3] # = [2 , 3]
L[: −1] # = [1 , 2]
L . append ( 4 ) # −> [ 1 , 2 , 3 , 4]
L += [ 5 , 6 ] # −> [ 1 , 2 , 3 , 4 , 5 , 6]
del L [ 5 ] # −> [ 1 , 2 , 3 , 4 , 5]
len (L) # = 5
L . reverse () # −> [ 5 , 4 , 3 , 2 , 1]
L . sort () # −> [ 1 , 2 , 3 , 4 , 5]
Variables only hold references to lists (like to everything else):
M= L
M[ 2 ] = ”A” # −> [ 1 , 2 , ”A” , 4 , 5 ]
L[2] # −> ”A”

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Dictionaries and sets


Dictionaries:
D = { ” Mozart ” : 1 7 5 6 , ” S c h u b e r t ” : 1797}
D[ ” Mozart ” ] # = 1756
D. keys ( ) # = [ ’ S c h u b e r t ’ , ’ Mozart ’ ]
D. v a l u e s ( ) # = [1797 , 1756]
D. update ({ ” Beethoven ” : 1770})
D[ ” E i n s t e i n ” ] = 1879
” E i n s t e i n ” in D # = True
l e n (D) #= 4
D . g e t ( ” Newton ” , ” unknown ” ) # = ’ unknown ’
Sets:
s = set ( [ 1 , ” h e l l o ” , ” world ” ] )
s . add ( 3 )
2 in s # = False

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Output and string formatting


Basic printing
p r i n t ” two : ” , 2 , ” f o u r : ” , 4 # two : 2 f o u r : 4
p r i n t ” %0.2 f + %d = %0.2 f ” % ( 2 . 5 , 2 , 2.5+2)
# 2.50 + 2 = 4.50
str.format()
f o r m a t t e d = ” PI : { 0 : 0 . 2 f } ” . f o r m a t ( math . p i )
p r i n t f o r m a t t e d # PI : 3 . 1 4
Newline peculiarities:
p r i n t ” t e x t ” # a p p e n d s <n e w l i n e >
p r i n t ” t e x t ” , # a p p e n d s a s p a c e ( n o t e t h e comma )

import s y s
s y s . s t d o u t . w r i t e ( ” t e x t ” ) # appends nothing
http://docs.python.org/library/string.html#formatstrings
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

Control flow

i f n == 0 :
p r i n t ”n i s 0 ”
e l i f n > 0:
p r i n t ”n i s p o s i t i v e ”
else :
p r i n t ”n i s n e g a t i v e ”

• Indentation matters!
• Don’t mix tabs and spaces – configure your editor
appropriately!

while n > 0:
n −= 1

for n in [1 , 2 , 3 , 4 ] :
print n
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

Idioms
Iterate over a dictionary and format strings:
D = { ” Mozart ” : 1 7 5 6 , ” S c h u b e r t ” : 1797}
f o r name , y e a r i n D . i t e r i t e m s ( ) :
p r i n t ”%s was b o r n i n %d” % ( name , y e a r )
Enumerate list:
L = [ ” item1 ” , ” item2 ” , ” item3 ” , ” item4 ” ]
for i , item in enumerate (L ) :
p r i n t ”The l i s t c o n t a i n s %s a t i n d e x %d” \
% ( item , i )
List comprehensions:
quad = [ x ∗∗2 f o r x i n r a n g e ( 8 ) ]
# = [ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49]
e v e n = [ x ∗∗2 f o r x i n r a n g e ( 8 ) i f x % 2 == 0 ]
# = [ 0 , 4 , 16 , 36]
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

Files

values = [[1 , 0] , [1 , 1]]

# J o i n v a l u e s by ” , ” and l i n e s by n e w l i n e s
c s v t e x t = ’ \n ’ . j o i n ( ’ , ’ . j o i n ( s t r ( v a l u e ) \
for value in l i n e ) for l i n e in values )

# Write the t e x t i n t o a f i l e
c s v f i l e = open ( ’ f i l e . c s v ’ , ’w ’ )
c s v f i l e . write ( csvtext )
c s v f i l e . close ()

w i t h open ( ” m y f i l e . t x t ” ) a s f :
data = f . read ()
# do s o m e t h i n g
# f i l e i s c l o s e d upon l e a v i n g t h e ’ w i t h ’ b l o c k

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules
Qn
Functions: fac(n) = n! := k=1 k

def f a c ( n ) :
i f n == 1 :
return 1
else :
return n ∗ f a c ( n − 1)

def f a c ( n ) :
result = 1
for k in range (1 , n + 1 ) :
r e s u l t ∗= k
return r e s u l t

def f a c ( n ) :
r e t u r n r e d u c e ( lambda a , b : a ∗ b ,
range (1 , n + 1) , 1)

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Functions: Parameters
Parameters point to values (like all variables):
def c hange ( a , b ) :
a = b[0] = 0

a , b = 1 , [1 , 1]
c ha ng e ( a , b ) # −> a = 1 , b = [ 0 , 1 ]
Named Parameters:
def h e l l o w o r l d ( h e l l o=” H e l l o ” , w o r l d=” w o r l d ” ) :
print hello , world

helloworld () # −> ” H e l l o w o r l d ”
h e l l o w o r l d ( h e l l o=” Hi ” ) # −> ” Hi w o r l d ”
# p o s i t i o n does not matter :
h e l l o w o r l d ( w o r l d=” e a r t h ” , h e l l o=” Hi ” )
# −> ” Hi e a r t h ”
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

Functions: Parameters 2
Special list and keyword (dictionary) arguments
• starred for list, double-starred for dictionary
• Enable arbitrary number of arguments
• Restriction if used in combination: keyword arguments need
to be after the list arguments
def f u n ( ∗ a r g s , ∗∗ k w a r g s ) :
# do s o m e t h i n g w i t h v a l u e s
f u n ( ” some ” , ” l i s t ” , ” v a l u e s ” ,
w i t h=” k e y ” , v a l u e=” p a i r s ” , a s=” d i c t i o n a r y ” )
E.g.:
def sum ( ∗ v a l u e s ) : # sum ( 1 , 2 , 5 ) = 8
result = 0
for value in values :
r e s u l t += v a l u e
return r e s u l t
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

Iterables

• Basically everything you can use in for .. in ..


• e.g.

m y l i s t = [ x ∗∗2 f o r x i n r a n g e ( 2 , 5 ) ]
for i in mylist :
print i

mystr = ” h e l l o w o r l d ”
for char in mystr :
print char

• Can be read multiple times


• Downside: Everything is in memory as a whole

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Generators
• Special iterables that generate values on the fly
• Not in memory as a whole
• Thus, only readable once
Same example as before, with generators:
# note the d i f f e r e n t braces
mygen = ( x ∗∗2 f o r x i n r a n g e ( 2 , 5 ) )
p r i n t mygen # −> <g e n e r a t o r o b j e c t . . . >
f o r i i n mygen :
print i

# a s e c o n d l o o p won ’ t p r i n t a n y t h i n g a s t h e
# g e n e r a t o r a l r e a d y went t h r o u g h a l l i t e m s

• as soon as the loop wants to read a new value, it is


’generated’ from the comprehension rule given above
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

Generators 2

def r e v e r s e ( d a t a ) :
f o r i n d e x i n r a n g e ( l e n ( d a t a ) −1 , −1, −1):
y i e l d data [ index ]

for char in r e v e r s e ( ’ webscience ’ ) :


print char

• Yield temporarily suspends processing and remembers the


execution state
• Upon resume, the generator picks up where it left off
• More at
• docs.python.org/tutorial/classes.html#generators
• stackoverflow.com/a/231855

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Generators 3

Read file line by line and split by ’,’:


w i t h open ( ’ t e x t f i l e . t x t ’ , ’ r ’ ) a s f :
l i n e s = ( l i n e . r s t r i p ( ’ \n ’ ) . s p l i t ( ’ , ’ )
for l i n e in f )
for l i n e in l i n e s :
print l i n e # process here

E.g. if testfile.txt contains we get

one,two,three [’one’, ’two’, ’three’]


3,2,1 [’3’, ’2’, ’1’]

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Classes and objects

c l a s s Animal :
def i n i t ( s e l f , name ) :
s e l f . name = name
def s a y h e l l o ( s e l f ) :
p r i n t ” I ’m %s ” % s e l f . name

c l a s s Dog ( Animal ) :
def i n i t ( s e l f , name , owner ) :
s u p e r ( Dog , s e l f ) . i n i t ( name )
s e l f . owner = owner
def s a y h e l l o ( s e l f ) :
p r i n t ” H e l l o %s ” % s e l f . owner

dog = Dog ( ” C h a r l y ” , ” Mike ” )


dog . s a y h e l l o ( )

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Modules
Any Python file (e.g. mymodule.py) is a module and can be
imported:
import mymodule

mymodule . m y f u n c t i o n ( )

from mymodule import m y f u n c t i o n


from mymodule import ∗ # rather discouraged

myfunction ()
File-system directories can be used to create “namespaces”, if they
contain a file init .py (which may contain initialization code):
import m y d i r . mymodule
from m y d i r . mymodule import m y f u n c t i o n

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

main

Variable name contains the name of the current module. It


equals " main " when the script is run directly from the
command-line.
Common idiom:
def main ( ) :
print ” Hello world ! ”

if name == ” main ”:
main ( )

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

More advanced concepts

• exceptions
• multiple inheritance
• operator overloading
• metaclasses
• inline documentation and test code
• extensive “runtime” information

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

Regular expressions
re is a module for handling regular expressions.
import r e

r e . f i n d a l l ( ’ [ A−Za−z ]+ ’ , ’ H e l l o w o r l d ! ’ )
# = [ ’ Hello ’ , ’ world ’ ]
* 0 or more findall(pattern, string)
+ 1 or more match(pattern, string)
? 0 or 1 sub(pattern, repl, string)
[. . . ] certain characters split(pattern, string)
[^. . . ] characters excluded ...

Pre-compiling regular expressions:


WORD RE = r e . c o m p i l e ( ’ [ A−Za−z ]+ ’ )
WORD RE . f i n d a l l ( ’ H e l l o w o r l d ! ’ )

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

URLs
urllib2 is a module for opening URLs.
from u r l l i b 2 import u r l o p e n

u r l f i l e = u r l o p e n ( ” h t t p : / /www. g o o g l e . com” )
content = u r l f i l e . read ()
# = ’ <! d o c t y p e html><html > [ . . . ] < / s c r i p t >’
Basic HTTP authentication:
import u r l l i b 2
a u t h h a n d l e r = u r l l i b 2 . HTTPBasicAuthHandler ( )
a u t h h a n d l e r . a d d p a s s w o r d ( r e a l m= ’ t h e r e a l m ’ ,
u r i= ’ h t t p : / /www. e x a m p l e . com ’ ,
u s e r= ’ u s r ’ , passwd= ’ pwd ’ )
opener = u r l l i b 2 . b u i l d o p e n e r ( auth handler )
u r l l i b 2 . i n s t a l l o p e n e r ( opener )
u r l o p e n ( ’ h t t p : / /www. e x a m p l e . com/ r e s t r i c t e d ’ )
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

XML documents

xml.dom is a module for parsing XML documents and accessing


them using the Document Object Model.
from xml . dom . minidom import p a r s e S t r i n g

c o n t e n t = ”””<t a g a t t r =”1”>
<sub>t e x t </sub ></tag>”””
dom = p a r s e S t r i n g ( c o n t e n t )
dom . c h i l d N o d e s [ 0 ] . g e t A t t r i b u t e ( ’ a t t r ’ ) # = ’ 1 ’
s u b s = dom . getElementsByTagName ( ’ sub ’ )
subs [ 0 ] . childNodes [ 0 ] . nodeValue # = ’ text ’

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

JSON data

json is a module for parsing and exporting JSON data snippets.


import j s o n

j s o n d a t a = ’ {” l i s t ” : [ 1 , 2 ] , ” k e y ” : ” v a l u e ”} ’
contents = json . loads ( json data )
p r i n t c o n t e n t s [ ’ l i s t ’ ] # −> [ 1 , 2 ]
p r i n t c o n t e n t s [ ’ key ’ ] # −> v a l u e

Python Michael Muenzer


Introduction Language basics Advanced concepts Special modules

NetworkX
networkx is a module for the creation, manipulation, and study of
the structure, dynamics, and functions of complex networks.
[networkx.lanl.gov]
import n e t w o r k x a s nx

G = nx . Graph ( )
G. add node (1)
G. add edge (1 , 2)
G. add edge (2 , 3)
Plot graphs:
import m a t p l o t l i b . p y p l o t a s p l t

plt . figure ()
nx . draw (G)
p l t . s a v e f i g ( ’ g r a p h . png ’ )
Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules

NetworkX: Customized visualization


plt . figure ()
plt . axis ( ’ off ’)
p o s = nx . s p r i n g l a y o u t (G , i t e r a t i o n s =50)
nx . d r a w n e t w o r k x e d g e s (G , p o s )
nx . d r a w n e t w o r k x n o d e s (G , pos , [ 1 ] ,
n o d e c o l o r= ’ r ’ )
nx . d r a w n e t w o r k x n o d e s (G , pos , [ 2 , 3 ] ,
n o d e c o l o r= ’ b ’ )
nx . d r a w n e t w o r k x l a b e l s (G , p o s )
p l t . s a v e f i g ( ’ g r a p h . png ’ , d p i =72)

Python Michael Muenzer


Further reading

Official Python tutorial:


http://docs.python.org/tutorial/
Python tutorial at the University of Toronto: http:
//www.cs.toronto.edu/~gpenn/csc401/401_python_web/
Python 2.7 Quick Reference:
http://rgruet.free.fr/PQR27/PQR2.7.html
http://docs.python.org/library/re.html
http://docs.python.org/library/urllib2.html
http://docs.python.org/library/xml.dom.html
http://docs.python.org/library/json.html
NetworkX:
http://networkx.github.com/documentation/latest/

Python Michael Muenzer

You might also like