Python Tutorial Michael Muenzer Graz University of Technology March 18, 2013 Slides based on previous work by Jan P¨ oschko 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 # i n t e g e r x = 3.14159 # f l o a t x = ” Hello world ! ” # s t r i n g • No variable declarations • Dynamically typed String delimeters: s = ” Hello world ! ” s = ’ Hello world ! ’ s = ””” Hello world ! ””” # 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] l e n (L) # = 5 L . r e v e r s e () # − > [5 , 4 , 3 , 2 , 1] L . s o r t () # − > [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” : 1756 , ” Schubert ” : 1797 } D[ ”Mozart” ] # = 1756 D. keys () # = [ ’ Schubert ’ , ’ 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. get ( ”Newton” , ”unknown” ) # = ’ unknown ’ Sets: s = s e t ( [ 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 print ”two : ” , 2 , ” four : ” , 4 # two : 2 four : 4 print ”%0.2 f + %d = %0.2 f ” %(2.5 , 2 , 2.5+2) # 2.50 + 2 = 4.50 str.format() formatted = ”PI : { 0:0 .2 f } ” . format ( math . pi ) formatted # PI : 3.14 print Newline peculiarities: print ” t e x t ” # appends < newline > print ” t e x t ” , # appends a space ( note the comma) import sys sys . stdout . 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: print ”n i s 0” n > 0: e l i f print ”n i s p o s i t i v e ” else : print ”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” : 1756 , ” Schubert ” : 1797 } for name , year in D. i t e r i t e m s ( ) : print ”%s was born in %d” % (name , year ) Enumerate list: L = [ ” item1 ” , ” item2 ” , ” item3 ” , ” item4 ” ] i , item enumerate (L ) : for in print ”The l i s t c o n t a i n s %s at index %d” \ % ( item , i ) List comprehensions: quad = [ x ∗∗ 2 x in range ( 8 ) ] for # = [0 , 1 , 4 , 9 , 16 , 25 , 36 , 49] even = [ x ∗∗ 2 for x in range (8) i f x % 2 == 0] # = [0 , 4 , 16 , 36] Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules Files v a l u e s = [ [ 1 , 0] , [1 , 1 ] ] # Join v a l u e s by ” ,” and l i n e s by newlines c s v t e x t = ’ \ n ’ . j o i n ( ’ , ’ . j o i n ( s t r ( value ) \ for value in l i n e ) for l i n e in v a l u e s ) # 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 . csv ’ , ’w ’ ) c s v f i l e . w r i t e ( c s v t e x t ) c s v f i l e . c l o s e () with open ( ” m y f i l e . t x t ” ) as f : data = f . read () # do something # f i l e i s c l o s e d upon l e a v i n g the ’ with ’ block Python Michael Muenzer
Introduction Language basics Advanced concepts Special modules Functions: fac( n ) = n ! := � n k =1 k def fac (n ) : i f n == 1: return 1 else : return n ∗ fac (n − 1) def fac (n ) : r e s u l t = 1 for k in range (1 , n + 1 ) : r e s u l t ∗ = k return r e s u l t fac (n ) : def return reduce ( 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 change (a , b ) : a = b [ 0 ] = 0 a , b = 1 , [1 , 1] change (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=” Hello ” , world=” world ” ) : h e l l o , world print h e l l o w o r l d () # − > ” Hello world ” h e l l o w o r l d ( h e l l o=”Hi” ) # − > ”Hi world ” # p o s i t i o n does not matter : h e l l o w o r l d ( world=” earth ” , h e l l o=”Hi” ) # − > ”Hi earth ” 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 fun ( ∗ args , ∗∗ kwargs ) : # do something with v a l u e s fun ( ”some” , ” l i s t ” , ” v a l u e s ” , with=” key ” , value=” p a i r s ” , as=” 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 r e s u l t = 0 value v a l u e s : for in r e s u l t += value r e s u l t return 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 x in range ( 2 , 5 ) ] for for i in m y l i s t : i print 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 for x in range (2 ,5)) print mygen # − > < generator o b j e c t ... > i in mygen : for print i # a second loop won ’ t p r i n t anything as the # generator a l r e a d y went through a l l items • as soon as the loop wants to read a new value, it is ’generated’ from the comprehension rule given above Python Michael Muenzer
Recommend
More recommend