Python Quick Reference for Programmers by David Ljung Madison http://DaveSource.com/ GTK: http://www.baypiggies.org/10mintig.html can be used interactively as a calculator, results are printed _ is last result (readonly variable!) complex numbers: a+bj or (a+bj) - a.real() a.imag() and abs(a) round(var,dec_places) variables are just labels (unlike $perl) and have no type multi-assignment: a,b=b,a variables must be defined before use (or after 'del(var)') namespaces are the same as the module name (like perl) object oriented: functions of variables are called: var.func() [ex: str.len()] whitespace is important! indentation implies grouping (blocks) lines end in ';' or newline print puts spaces between items (,) and \n at end (unless ended with ,) sys.argv has arguments ctrl-d or sys.exit() to quit Strings: "string" 'string' can be indexed and index spliced a[-5] a[4:6] but are immutable (can't set index splices: a[0:2]=...) string math is done with + and * Can convert other datatypes to strings with repr(var) or `var` or str() (adds quotes, \control chars, etc..) or string.atoi(numvar) line-continuation with \ Extended strings start/end with ''' or """ (like shell/perl <: .. elif : .. else: .. for in : (don't modify list in loop!) for in range(): or range(,,[step]) for in : # Takes n items at a time continue to next iteration of enclosing loop break out of enclosing loop (don't execute loop 'else') loops can have else statements, only executed if we didn't break! pass nop Functions: def function_name(args): (end with extra newline) first line can be a "Docstring (string literal)." "Should start with capital letter, end with period." any assignments are local vars (like perl 'my') unless 'global' specified args are call by value (really call by object reference) is just a pointer and can be assigned: f=func return statements (like C,perl). "None" is default return value default argument values in arglist: = (evaluated only once) def f(a, l = []): l.append(a) # Accumulates values across calls def f(a, l = None): if l is None: l = [] # Only appends values for this call l.append(a) Calling can specify args by varname: func(var1=value, var2=value...) Last args can include '*' and '**' *name will get any arguments after the last one is used **name will get any arguments specified by undefined varnames lambda a,b : a+b (like perl: sub { anon_function; }) has new scope, but can reference current scope with default values: lambda a,b=localvar : a+b Lists: [a,b] # index starts at 0, can be nested, mutable a=[1,g,3] a[1] and g point to the same thing can do all the index splicing and are mutable: a[1:1]=[1,2] add some elements a[1:2]=[c,d] replace some elements a[:0]=a double the list b=a[:] b gets a *copy* of a (same as b=a[0:-1]) Packing: 'a=[1,2,3,4]' and unpacking: '[w,x,y,z]=a' list.insert(position,item) list.append(item) list.index(item) # error if no item list.remove(x) # just first item - error if no item list.sort() list.reverse() list.count(item) # number of times filter(func,list) # like perl grep map(func,list) # like perl map function of 'None' just returns it's arguments if multiple lists are used, calls function with item from each list map(None, list1, list2) # Interlaces two lists reduce(func,list) # call on first two, then result and next, result and.. reduce( lambda a,b: a+b , list) # Sums up a list del(list,[index_or_splice]) # Remove items by index(es) Tuples: a=1,2,3,4 (a,b) or a,b # () are optional if not ambigious Packing: 'a=1,2,3,4' and unpacking: 'w,x,y,z=a' can be nested immutable (but you can slice and concatenate) a='hi', is a tuple as opposed to a='hi' (note trailing comma) Dictionaries (hashes, associative arrays): {key1:val1, key:val2} Keys are strings or numbers or tuples of strings, numbers and tuples dict[key3]=val3; keys(dict) dict.has_key(key) dict.items() # key1,val1,key2,val2,... Expressions: includes common C operators can be chained: a in ; not in is ; is not Also: and, or, not Shortcut operators: and and, or or Comparisons can be done on complex data types, they are done recursively on each item in order (index or ascii). If items are different types: list import from mod import * (doesn't get _underscorevars) Modules searched for: env:$PYTHONPATH (or list at sys.path()) dir([module]) lists names in [module] namespace (not builtins) Use __builtin__ module to see builtin namespace Modules can be in a directory 'package': import dir.dir.mod; Each directory must have __init__.py can do: from dir.dir import mod (so the namespace is just 'mod') if __init__.py defined __all__, then 'from dir.dir import *' works packages are searched first for modules before normal search path Compiled Python: platform independent only speeds up loading, not execution (pre-interpreted into byte code) module.pyc (compiled) is used instead of module.py if available and modtime stored in .pyc matched mod time of .py Output: ; (if in interactive mode) print items... write to sys.stdout print "format string %d %d hi" % a,b string.rjust(,length) .ljust, .center, .zfill (zero fill) Can specify dictionary elements by name in format string: "format %(keya)d, %(keyb)s" % dict; # useful with vars() Files: f=open(,[mode='r']) modes: r,w,a,r+ f.read([bytes=infinite]) returns "" if at eof f.readline(), f.readlines() f.write(str) f.tell() and f.seek(offset,from_what=0) 0=beg, 1=curr, 2=end Pickling: Read and write most complex datatypes to files (or to strings)! pickle.dump(object,file) object=pickle.load(file) See pickle reference for more info Exceptions: try: except : ... Can do: except (,): and else: Exception handlers can take an argument: except , : raise , (to make up names, use a string variable) finally: block outdside of try: is always executed, exception or not