Python Full Meal Handout
Python Full Meal Handout
Matt Harrison http://panela.blog-city.com/ matthewharrison at gmail.com Note that examples are illustrated as if they were done in a terminal. (This file can also be executed using doctest.testfile)
>>> "0.3f 0.2f" 0 (20+ !/3.) 1 for-at as float &ith 3 deci-al (laces %20.000 0.33%
%li4ard%
Whitespace
Instead of using { or } use a : and indent consistently (4 spaces is recommended practice)
Conditionals
>>> >>> ... ... ... ... ... ... A grade = "5 if grade > "07 (rint "A" elif grade > >07 (rint "?" else7 (rint "@"
Variables
>>> a = 5 >>> b = "A string"
Looping
while
>>> n5- = 2 >>> &hile n5- > 07 ... (rint n5... n5- = n5- = ! 2 !
Numbers
>>> 2 + 2 4
Functions
>>> def add65(n5-ber)7 ... ret5rn n5-ber + 5 ... >>> add65(2) 7
for
>>> for n5- in range(2+ 0+ =!)7 ... (rint n52 !
docstrings
>>> def add(n5-ber=0+ defa5lt=#)7 ... "add defa5lt to n5-ber" ... ret5rn n5-ber + defa5lt ... >>> add(!) 7 >>> add(30+ 40) 70 >>> add(defa5lt=2) 2 >>> add(defa5lt=3+ n5-ber=") 1 note order of args !2
Slicing fun
Indexes Individual indexes can be picked out of sequences
>>> fa<orite6(et = (ets203 >>> fa<orite6(et %dog% >>> re(tile = (ets2=!3 >>> re(tile
>>> for n5- in range(!00)7 ... (rint n5... if n5- == !7 ... brea* 0 !
Formatting
>>> "0d" 0 20 %20%
continue
float
filter
Catching Exceptions
>>> tr'7 ... 2!+ 23.re-o<e(3) ... eEce(t Fal5e8rror+ e7 ... (rint "Ge-o<ing bad n5-ber" ... eEce(t 8Ece(tion+ e7 ... (rint "Beneric 8rror" 1 eEa-(le to sho& eEce(tion chaining ... 1 since the (re<io5s eEce(tion &as ca5ght+ this does nothing ... else7 ... 1 no eEce(tions ... (rint "8$C8" ... finall'7 ... 1 al&a's eEec5tes (after else )+ so 'o5 can clean5( ... (rint "HIJ8" Ge-o<ing bad n5-ber HIJ8
Classes
>>> class Ani-al(ob9ect)7 ... def 66init66(self+ na-e)7 ... self.na-e = na-e ... ... def tal*(self)7 ... (rint "Beneric gro&l" ... >>> ani-al = Ani-al("thing") >>> ani-al.tal*() Beneric gro&l
Importing Libraries
>>> i-(ort -ath >>> -ath.sin(!) 0.>4!470">4>07>"#5
__init__ is a constructor.
>>> class @at(Ani-al)7 ... def tal*(self)7 ... "C(ea* in cat tal*" ... (rint "0s sa'%s %Deo&.%" 0 (self.na-e) >>> cat = @at("Bro5cho") >>> cat.tal*() Bro5cho sa'%s %Deo&.%
Functional Programming
lambda
File Input/Output
(Importing tempfile to create temporary files)
>>> i-(ort te-(file
Exceptions
Raising Exceptions
map
Decorator Template
>>> def decorator(f5nc6to6decorate)7 ... 1 5(date &ra((er.66doc66 and .f5nc6na-e ... 1 or Kf5nctools.&ra(s(&ra((er) ... def &ra((er( args+ *&)7 ... 1 do so-ething before in<ocation ... res5lt = f5nc6to6decorate( args+ *&) ... 1 do so-ething after ... ret5rn res5lt ... ret5rn &ra((er
File output
>>> >>> >>> >>> >>> filena-e = te-(file.-*te-(() fo5t = o(en(filena-e+ %&%) fo5t.&rite("fooAn") fo5t.&rite("barAn") fo5t.close()
By default the eEce(tions module is loaded into the 66b5iltins66 namespace (see dir(66b5iltins66)).
>>> def add62(<al5e)7 ... if not isinstance(<al5e+ (int+ float))7 ... raise ,'(e8rror("0s sho5ld be an int or float" 0 str(<al5e)) ... ret5rn <al5e + 2 >>> add62("foo") ,racebac* (-ost recent call last)7 ... ,'(e8rror7 foo sho5ld be an int or
reduce
File input
>>> fin = o(en(filena-e) >>> lines = fin.readlines()
Same as:
>>> nested = 23 >>> for E in Erange(3)7 ... for ' in Erange(4)7 ... nested.a((end((E+'))
Generator expressions Like list comprehensions. Except results are generated on the fly. Use ( and ) instead of 2 and 3 (or omit if expecting a sequence)
>>> 2E E for E in Erange(5)3 20+ !+ 4+ "+ !#3 >>> (E E for E in Erange(5)) 1 doctest7 +8$$MOCMC+ Ngenerator ob9ect NgeneE(r> at ...> >>> list(E E for E in Erange(5)) 20+ !+ 4+ "+ !#3
Iteration Protocol
>>> seL5ence = 2 %foo%+ %bar%3 >>> seL6iter = iter(seL5ence) >>> seL6iter.neEt() %foo% >>> seL6iter.neEt() %bar% >>> seL6iter.neEt() ,racebac* (-ost recent call last)7 ... Cto(Mteration
%66gt66%+ %66hash66%+ %66init66%+ %66le66%+ %66len66%+ %66lt66%+ %66-od66%+ %66-5l66%+ %66ne66%+ %66ne&66%+ %66red5ce66%+ %66red5ce6eE66%+ %66re(r66%+ %66r-od66%+ %66r-5l66%+ %66setattr66%+ %66str66%+ %ca(itali4e%+ %center%+ %co5nt%+ %decode%+ %encode%+ %ends&ith%+ %eE(andtabs%+ %find%+ %indeE%+ %isaln5-%+ %isal(ha%+ %isdigit%+ %islo&er%+ %iss(ace%+ %istitle%+ %is5((er%+ %9oin%+ %l95st%+ %lo&er%+ %lstri(%+ %(artition%+ %re(lace%+ %rfind%+ %rindeE%+ %r95st%+ %r(artition%+ %rs(lit%+ %rstri(%+ %s(lit%+ %s(litlines%+ %starts&ith%+ %stri(%+ %s&a(case%+ %title%+ %translate%+ %5((er%+ %4fill%3 >>> hel(("".s(lit) 1 sho&s "".s(lit.66doc66 Rel( on b5ilt=in f5nction s(lit7 N?$AJS$MJ8> s(lit(...) C.s(lit(2se( 2+-aEs(lit33) => list of strings N?$AJS$MJ8> Get5rn a list of the &ords in the string C+ 5sing se( as the deli-iter string. Mf -aEs(lit is gi<en+ at -ost -aEs(lit s(lits are done. Mf se( is not s(ecified or is Jone+ an' &hites(ace string is a se(arator. N?$AJS$MJ8>
Scripts
Making instances iterable
>>> class Mter(ob9ect)7 ... def 66iter66(self)7 ... ret5rn self ... def neEt(self)7 ... 1 ret5rn neEt ite-
Instead of having globally executed code create main function and invoke it like this
>>> def -ain(arg5-ents)7 ... 1 do logic here ... 1 ret5rn eEit code >>> if 66na-e66 == "66-ain66"7 ... s's.eEit(-ain(s's.arg<))
Debugging
gdb like debugging is available
>>> i-(ort (db >>> 1(db.set6trace() 1co--ented o5t for doctest to r5n
List Comprehension
>>> res5lts = 2 2 E for E in seL A ... if E >= 0 3
Generators
Getting Help
Functions with 'ield remember state and return to dir and hel( or .66doc66 are your friends it when iterating over them
>>> def gen6range(end)7 ... c5r = 0 ... &hile c5r N end7 ... 'ield c5r ... 1 ret5rns here neEt ti-e ... c5r += ! >>> dir("") 1 doctest7 +JIGDA$MP86QRM,8COA@8 2%66add66%+ %66class66%+ %66contains66%+ %66delattr66%+ %66doc66%+ %66eL66%+ %66ge66%+ %66getattrib5te66%+ %66getite-66%+ %66getne&args66%+ %66getslice66%+