Page by: Gareth.
Original for this page can be found here

Another page for Python Quick Reference(s) can be found there

Python for the Impatient

This is a very brief summary of the Python language for computing professionals and other folks who are happy learning a new language in ten minutes from a couple of pieces of paper.

Types

Python is dynamically/latently/weakly typed, so values rather than variables have types. Main types:

Expression syntax

Much like most languages. Infix notation, parens for grouping. Comparisons use same syntax as C (== for equality testing, != for inequality testing), but also have is and is not for identity testing (things can be equal but not identical), and NB that chaining of comparison operators like 1 <= a <= 1000 makes sense. ^ is xor as in C; ** is exponentiation as in Fortran. / when applied to integers does integer division: this is a serious potential pitfall. % does mod.

Comments begin with # and extend to end of line.

Assignment is x=y. You can do x=y=z as in C. Also x,y=a,b does a parallel assignment, so e.g. you can say x,y=y,x to swap.

Boolean operators: and, or, not are short-circuiting and have low precedence. & etc are bitwise and not short-circuiting.

Basic control structures

Structure is indicated by indentation, as in occam. You can group statements on a single line with semicolons to separate, but normally no statement terminators are needed. The null statement is written pass . If the body of a construct will fit on the same line as its "head" then you can do that, as illustrated below


        if condition:            if condition: stuff
          stuff                  elif condition: stuff
        elif condition:          else: stuff
          stuff
        else:
          stuff

        while condition:         while condition: stuff
          stuff

        for var in list/tuple:   for var in list/tuple: stuff
          stuff
You can use for to simulate a BASIC-ish FOR with the range function. range(a,b) is a list containing numbers from a (inclusive) to b (exclusive). An optional third parameter is the "step". For large loops of this kind, use xrange instead of range to avoid generating a lot of garbage.

You can give a loop an else clause. It will be executed iff the loop ended naturally. To exit a loop unnaturally, use break (alas, Python doesn't have multi-level breaks like Perl and Java). There's also continue, same as in C.

Functions

Define with def funname(arglist): stuff . Most arg lists are just comma-separated lists of variables. Can give default values: def foo(x,y=3,z=7): .... When calling, can omit defaultable vars. Can give keyword-style args: foo(z=9) .

Variables

Scopes: one global per module, one local per function invocation. No scoping corresponding to block structure as in C, Pascal, etc. You can get dictionaries corresponding to the current namespaces with globals() and locals().

A variable in a function is local iff it's assigned to and not explicitly declared global by a global x,y,z statement in the function.

Classes and instances

Same syntax for attribute (= member, instance variable) and method (= member function) references as C++, Java, Modula-3: x.attribute, x.method(). To define a class:

class Foo:
          stuff
where stuff is a bunch of definitions. Functions defined here are methods. def foo(self,x,y) is invoked by instance.foo(x,y). Variables defined here are really attributes. Variable references within a class definition aren't implicitly interpreted as attribute references as in C++.

To make a subclass, do

class Foo(Bar,Baz,Quux):
          ...
(yes, Python has multiple inheritance).

Exceptions

Exceptions are classes (they can be strings, but classes are better because you can have a hierarchy). Raise with raise exception or raise exception,arg. Catch with


        try: stuff
        except exception1: stuff
        except exception2,arg: stuff
        except (exc3,exc4,exc5),arg: stuff
        except: stuff
        else: stuff
        finally: stuff
The unqualified except catches all exceptions not already handled. The else is done if an exception wasn't raised. The finally is done whether or not one was. For some reason, you can't use finally and except together.

Modules

A module is (1) a global namespace, (2) a file of Python code that will be executed in its own namespace. The contents of the namespace of module foo are available: what foo calls x, anything else can call foo.x after doing import foo. You can snarf (some of) a module's contents into your current global namespace by saying from foo import blah,weeble , or all of it (eeek!) with from foo import * .

There are lots of standard modules. Some notable things in a few of them (mostly functions, but some variables too; these are meant to be suggestive and illustrative, and are certainly nowhere near exhaustive):

Useful operations on built-in types

I/O

print x,y,z puts spaces between them and finishes up with a newline. A trailing comma replaces the newline with a space. You can also use the write method of sys.stdout .

input(string) uses string as a prompt, gets a line of input, evaluates it and returns it. raw_input(string) does the same but doesn't evaluate. Things like string.atoi() may be useful.

The string module has some useful formatting things. Another useful trick is the % operator, which does something odd when its LH operand is a string. The string should be more or less a C-style printf format string. (But %s will work for any kind of object.) The RH operand can be a sequence, whose values will be fed in order to the format directives in the string. Or, make it a dictionary and do this: "foo=%(foo)s bar%(bar)s" % {foo:123,bar:321} . This last trick cooperates nicely with locals() .

open(name,'r') returns a file object. (The second argument is as for C's fopen.) File objects have methods read(size), read() (reads whole file), readline(), readlines() (returns list of all lines); write(string); tell() and seek(offset); close() .

Random other facts

Python has automatic memory management, so you needn't bother freeing things when you're finished with them. Functions are first-class objects. You can nest function definitions, but NB that according to Python's scoping rules the inner functions can't see the outer functions' variables. You can get some way towards fixing this using default arguments. [This has been fixed anyway in Python 2.1, where the three-scope system has been replaced with fully nested scopes] Page by: Gareth.   Last updated: Mark 24.03.2001