Professional Documents
Culture Documents
Python: Tutorial
Python: Tutorial
Tutorial
Michael Muenzer
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”
Installing Python
Invoking Python
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
Booleans
not A
A and B
A or B
Comparisons: ==, !=, <, <=, >, >=
2 == 2
1 < 2 <= 3
1 == 2 and ”3” or ” 4 ” # = ”4”
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”
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
# 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
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)
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
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
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
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 ]
Generators 3
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
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 ( )
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
main
if name == ” main ”:
main ( )
• exceptions
• multiple inheritance
• operator overloading
• metaclasses
• inline documentation and test code
• extensive “runtime” information
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 ...
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
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 ’
JSON data
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
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