http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python
Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional Strong and dynamic typing (incl. duck typing) Late (dynamic) binding Multiple-inheritance, meta-classes Stuff you ll cover in the OOP course. Python: Operative Keywords Lambda functions and closure Built-in lists, tuples, and maps List comprehension Operator overloading Garbage collected Using the language well == writing pythonic code
Syntax From least to most surprising: Identifiers: [_a-za-z][_a-za-z0-9]*, case-sensitive # comment lines start with # Literal strings 'in single' "or double" quotes Also supports Unicode, Raw, and Multiline strings No char type Semicolons optional No block delimiters ({...}); use indentation instead String Literals Simple: 'in quotes' or "double quotes" Either can contain the other kind, unescaped. Normal escapes:\n \t \r \\etc. Strings can continue\ on next line "שלום" u Unicode: Raw: r"escapes\nare\nignored" Will contain \ and n as part of the string. Can be multiline. """Multi-line strings can be easily created by triple quotes (or triple double-quotes)"""
No Multi-Line Comments # Python only has to-end-of-line comments. # There s no equivalent of /*... */ multi-line comments in C-family languages. """However, any expression with no side-effect can be thought of as a comment. In particular, this includes multi-line strings!""" Quick (and Dirty) No return type def qsort1(lst): No argument type if len(lst) < 2: Built-in list type return lst Block-opening statements (def, if, pivot = lst[0] while...) end with : ; blocks i, left, right, eq = 0, [], [], [] delimited by indent. while i < len(lst): Variables not declared in advance v = lst[i] List access (lst[0]) List literals: [], [v] if v < pivot: Multiple assignment right += [v] if/elif/else elif v > pivot: No i++ left += [v] + used for list concatenation else: eq += [v] i += 1 return qsort1(right) + eq + qsort1(left)
Quick (still Dirty) def qsort2(lst): for statement is very different than the C-style variant. if len(lst) < 2: return lst; pivot = lst[0] left, right, eq = [], [], [] for v in lst: if v < pivot: right += [v] elif v > pivot: left += [v] else: eq += [v] return qsort2(right) + eq + qsort2(left) Slightly Less Quick (but Less Dirty) List comprehension. def qsort3(lst): if len(lst) < 2: return lst; pivot = lst[0] right = [v for v in lst if v < pivot] eq = [v for v in lst if v == pivot] left = [v for v in lst if v > pivot] return qsort3(right) + eq + qsort3(left)
Optional Arguments & Docstring def qsort4(lst, comp = cmp): '''Sorts the input list, using the provided function as a comparator. Default comparison function is cmp.''' if len(lst) < 2: return lst; pivot = lst[0] Docstring is an opening multiline string-comment. Extracted by tools as the documentation for the function. Can you spot the bug in this code? right = [v for v in lst if comp(v, pivot) < 0] eq = [v for v in lst if comp(v, pivot) == 0] left = [v for v in lst if comp(v, pivot) > 0] return qsort4(right) + eq + qsort4(left) Invocation Alternatives qsort4([34,1,32,56,23,1,324,3124,5,4,3,2,46,7]) qsort4([34,1,32,56,23,1,324,3124,5,4,3,2,46,7], lambda x, y: -cmp(x,y)) qsort4(comp = lambda x, y: cmp(y,x), lst = [34,1,32,56,23,1,324,3124,5,4,3,2,46,7])
Help! Help! Try these at the Python prompt: help(5) dir(5) dir([]) cmp. doc print cmp. doc help(cmp) dir(cmp) help(qsort4) Python Files #!/usr/bin/python2.4 # or: #!/usr/bin/python; but things change # between versions. import sys # or: from sys import argv, exit def main: for arg in sys.argv: print arg sys.exit(0) Bang line: specific version recommended import mechanism (not include ) name idiom: even in non-programs, often add main(), with test functionality. if name == " main ": main()
Closures and Lambdas def ratio(a, b): def rat(x): return x / (a+b) print rat(a), rat(b) def makeadder(incr): def add(x): return x + incr return add def makeadderusinglambda(incr): return lambda x: x + incr More About Lists [ can be of, 17, different types, True] range(5) = [0,1,2,3,4] Useful in for loops: for iin range(10) However, not generated lazily... Emulate enums: (apple, orange, kiwi) = range(3) range(2,5) => [2,3,4] Accessing specific elements: lst[i] = the i th element, 0-based lst[-i] = the i th -from-end element, 1-based range(5)[-1] => 4 # last element
Back to Quick (and Dirty) def qsort5(lst): if len(lst) < 2: return lst; pivot = lst[0] def lt(x): return x < pivot def eq(x): return x == pivot def gt(x): return x > pivot right = filter(lt, lst) Local functions, with closure. Filter function: specific variant of list comprehension. Dynamic typing: reuse of eq eq = filter(eq, lst) left = filter(gt, lst) return qsort5(right) + eq + qsort5(left) Slicing list[i:j] = from i(inclusive) to j (exclusive) lst= [ a, b, c, d, e, f, g ] lst[2:5] => [ c, d, e ] list[i:] = from i(inclusive) onwards lst[4:] => [ e, f, g ] list[:j] = from 0 to j (exclusive) lst[:2] = [ a, b ] list[:] = the entire list Slicing also works for strings! therapist [3:] => rapist hello [:-1] => hell
Removing Stuff del list[2] Shifts content after the deleted element del list[5:] del list[-2:] del list[4:9] But also: list[2:2] = [] list[5:] = []... etc. Mutability Lists are mutable; sort(lst) is in-place. But sorted(lst) returns a sorted copy. Assignment of lists is reference assignment. a = range(3); b = a; a[2] =? ; print b[2]? Update by slicing: lst[2:3] = [True, Hello ] lst[4:4] = [ insert, after, 4] lst[4:] = [] Strings are immutable. Cannot assign by slicing. No method modifies a string only returns a modified copy. As in Java.
Tuples Immutable lists of pre-defined size. However, tuple members could be mutable. Some tuple values: (3, hi, True) ( a, b ) ( a,) Dicts Maps in Python are called dicts (short for dictionaries ). Almost any object is a dictionary. Dict literals: {k1:v1, k2:v2,...} Examples: d1 = { name : joe, id : 1234} d2 = {0: a, 1: b, other : z } # non-string keys d3 = {} Keys must be of a hashabletype. Has hash and ( eq and/or cmp ) Hash value never changes Can any of the following serve as a key? (7, 7, 2) [7, 7, 2] (7, 7, { x : 2})
Accessing Dict Content mydict[ key ] = something something = mydict[ key ] if key in mydict: dosomething() oops = mydict[ nosuchkey ] Throws KeyError mydict[ nosuchkey ] = value OK, adds new key del mydict[ somekey ] something = mydict.get( key ) mydict.get( key ) = something Won t compile mydict.get( nosuchkey ) None But note that None could be the value of the key! Iterating Over Dicts for k in d.keys(): print k for k in d: print k for k in d: print d[k] for v in d.values(): print v for e in d.items(): print e Prints (key,value) tuples for k, v in d.items(): print k, :, v
String % Operator String class has a printf-like operator: % str = %d bottles of %s on the wall % (99, beer ) Allows key-based extraction from dicts: str = %(amount) bottles of %(drink) on the wall % { drink : beer, brand : Karlsberg, amount : 99} So, Do You Know Python Now? Spouse of me this night today manufactures the unusual meal in a home. You will join? Guy L.Steele, Jr., in forward to Effective Java, 2e There s a difference between knowing the grammar [syntax], and even the vocabulary [libraries], of a language, to knowing how to use it properly. However, at this stage, you should be able to read, and understand, most non-oo Python code.