0% found this document useful (0 votes)
57 views

Python Full Meal Handout

This document provides a summary of key Python concepts in 3 sentences or less: Python Full Meal provides an overview of Python concepts like variables, data types, conditionals, loops, functions, classes, exceptions, files, modules, and more. Key constructs are illustrated with examples like slicing lists, using dictionaries, defining functions, and catching exceptions. The document also covers more advanced topics such as decorators, generators, list comprehensions, and functional programming concepts in Python.

Uploaded by

chuff6675
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Python Full Meal Handout

This document provides a summary of key Python concepts in 3 sentences or less: Python Full Meal provides an overview of Python concepts like variables, data types, conditionals, loops, functions, classes, exceptions, files, modules, and more. Key constructs are illustrated with examples like slicing lists, using dictionaries, defining functions, and catching exceptions. The document also covers more advanced topics such as decorators, generators, list comprehensions, and functional programming concepts in Python.

Uploaded by

chuff6675
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Full Meal

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)

Slicing into a list

Lists, tuples and dictionaries


Lists
>>> (ets = 2"dog"+ "cat"+ "bird"3 >>> (ets.a((end("li4ard") >>> (ets 2%dog%+ %cat%+ %bird%+ %li4ard%3

Slices can also return lists (and use an optional stride)


>>> (ets2723 2%dog%+ %cat%3 >>> (ets2!73 2%cat%+ %bird%+ %li4ard%3 >>> (ets27723 2%dog%+ %bird%3

Conditionals
>>> >>> ... ... ... ... ... ... A grade = "5 if grade > "07 (rint "A" elif grade > >07 (rint "?" else7 (rint "@"

Variables
>>> a = 5 >>> b = "A string"

Variables aren't "typed" so they can contain anything


>>> b = 45.4 >>> b = "another string"

Tuples tuples are non-mutable


>>> t5(le6(ets = ("dog"+ "cat"+ "bird") >>> t5(le6(ets.a((end("li4ard") ,racebac* (-ost recent call last)7 ... Attrib5te8rror7 %t5(le% ob9ect has no attrib5te %a((end%

String slicing Strings (and most sequency things) can be sliced


>>> <eg = "to-atoe" >>> correct = <eg27=!3 >>> correct %to-ato% >>> <eg27723 %t-te% >>> <eg277=!3 1 bac*&ards stride. %eota-ot%

Looping
while
>>> n5- = 2 >>> &hile n5- > 07 ... (rint n5... n5- = n5- = ! 2 !

Numbers
>>> 2 + 2 4

Integer division - coerce to float if needed


>>> 3 / 4 0 >>> 3 / float(4) 0.75

Dictionaries Dictionaries (also known as hashmaps or associated arrays in other languages)


>>> (erson = :"na-e"7 "fred"+ "age"7 2"; >>> (erson2"age"3 2" >>> (erson2"-one'"3 = 5.45 >>> del (erson2"age"3 >>> (erson :%-one'%7 5.4500000000000002+ %na-e%7 %fred%;

Functions
>>> def add65(n5-ber)7 ... ret5rn n5-ber + 5 ... >>> add65(2) 7

for
>>> for n5- in range(2+ 0+ =!)7 ... (rint n52 !

No integer overflow! ('L' for long ints)


>>> 4 20 !0""5!!#2777#$

break out of loop

Strings Specify with single, double or triple quotes


>>> >>> >>> not ... ... hello = %&orld% sa'ing = "ain%t ain%t a &ord" (aragra(h = """)ran* said+ ",hat%s a &a' to tal* to an econo-ist." /oe re(lied.... """

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%

Python Full Meal 1/3

continue

Can contin5e to next item in loop iteration


>>> for n5- in range(!0)7 ... if n5- 0 2 == 07 ... contin5e ... (rint n5! 3 5 7 "

>>> fin.close() >>> lines 2%fooAn%+ %barAn%3

float

filter

(Delete temp file)


>>> i-(ort os >>> os.re-o<e(filena-e)

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

Return a sequence items for which f5nction(ite) is ,r5e


>>> filter(la-bda E7E >= 0+ 20+ =!+ 3+ 4+ =23) 20+ 3+ 43

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

Notes about "functional" programming in Python


s5- or for loop can replace red5ce

Importing Libraries
>>> i-(ort -ath >>> -ath.sin(!) 0.>4!470">4>07>"#5

List comprehensions replace -a( and filter

*args and **kw


>>> def (ara-6f5nc(a+ b=%b%+ args+ *&)7 ... (rint 2E for E in 2a+ b+ args+ *&33 >>> (ara-6f5nc(2+ %c%+ %d%+ %e+%) 22+ %c%+ (%d%+ %e+%)+ :;3 >>> args = (%f%+ %g%) >>> (ara-6f5nc(3+ args) 23+ (%f%+ %g%)+ ()+ :;3 >>> (ara-6f5nc(4+ args) 1 tric*se'. 24+ %f%+ (%g%+)+ :;3 >>> (ara-6f5nc( args) 1 tric*se'. 2%f%+ %g%+ ()+ :;3 >>> (ara-6f5nc(5+ %E%+ args) 25+ %E%+ (%f%+ %g%)+ :;3 >>> (ara-6f5nc(#+ :%foo%7%bar%;) 2#+ %b%+ ()+ :%foo%7 %bar%;3

Can also rename imports using as


>>> i-(ort -ath as -ath6lib >>> -ath6lib.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&.%

Can also import certain parts of libraries


>>> fro- -ath i-(ort sin >>> sin(!) 0.>4!470">4>07>"#5

Functional Programming
lambda

Create simple functions


>>> def -5l(a+ b)7 ... ret5rn a b >>> -5l62 = la-bda a+ b7 a b >>> -5l62(4+ 5) == -5l(4+5) ,r5e

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

Apply a function to items of a sequence


>>> -a((str+ range(3)) 2%0%+ %!%+ %2%3

reduce

Apply a function to pairs of the sequence


>>> i-(ort o(erator >>> red5ce(o(erator.-5l+ 2!+2+3+43) 24 1 ((! 2) 3) 4

File input
>>> fin = o(en(filena-e) >>> lines = fin.readlines()

Python Full Meal 2/3

Parameterized decorators (need 2 closures)


>>> def li-it(length)7 ... def decorator(f5nction)7 ... def &ra((er( args+ *&)7 ... res5lt = f5nction( args+ *&) ... res5lt = res5lt27length3 ... ret5rn res5lt ... ret5rn &ra((er ... ret5rn decorator >>> Kli-it(5) 1 notice (arens ... def echo(foo)7 ret5rn foo >>> echo(%!2345#%) %!2345%

Nested List Comprehensions


>>> nested = 2 (E+ ') for E in Erange(3) A ... for ' in Erange(4) 3 >>> nested 2(0+ 0)+ (0+ !)+ (0+ 2)+ (0+ 3)+ (!+ 0 )+ (!+ !)+ (!+ 2)+ (!+ 3)+ (2+ 0)+ (2+ !)+ (2+ 2)+ (2+ 3)3

>>> (rint 2E for E in gen6range(2)3 20+ !3

Making instances generate


>>> class Benerate(ob9ect)7 ... def 66iter66(self)7 ... 1 ret5rns a generator ... ret5rn self.neEt() ... def neEt(self)7 ... 1 logic ... 'ield res5lt

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>

Class instances as decorators


>>> class Hecorator(ob9ect)7 ... 1 in 66init66 set 5( state ... def 66call66(self+ f5nction)7 ... def &ra((er( args+ *&)7 ... 1 do so-ething before in<ocation ... res5lt = self.f5nction( args+ *&) ... 1 do so-ething after ... ret5rn res5lt ... ret5rn &ra((er >>> decorator = Hecorator() >>> Kdecorator ... def nothing()7 (ass

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%+

Shorthand for accumulation:


>>> res5lts = 23 >>> for E in seL7 ... if E >= 07 ... res5lts.a((end(2 E)@an be nested

Python Full Meal 3/3

You might also like