Python course: Home - Worksheets - Package - Developers - Licence - Credits
Python course: Home - Worksheets - Package - Developers - Licence - Credits
Gareth McCaughan, 1999
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.
Python is dynamically/latently/weakly typed, so values rather than variables have types. Main types:
12345, float 1.234e56,
long integer 123456789876543212345678987654321L,
complex 1+3j.
(1,2,3) (immutable),
list [1,2,3] (mutable),
dictionary {1:'a', 2:3, 3:(4,5,6)}.
Tuples and lists are like arrays, not like Lisp lists.
Index all these with []. Dictionary keys
must be of immutable types. Tuples and lists are indexed
from 0 on the left, or from -1 on the right, and allow
you to say x[2:5] meaning elements 2,3,4.
'abc' or "abc". No Perl-style
string interpolation with either syntax. C-style escapes.
Strings behave like tuples of length-1 strings.
None.
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.
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.
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) .
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.
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 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.
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):
sys.argv, sys.exit,
sys.stdin.
math.sin, math.pi.
string.lower, string.find,
string.split.
os.rename, os.system,
os.rmdir.
re.compile, re.match.
whrandom.randint.
d.items() is a list of 2-tuples
(k,v). d.keys(), d.values().
d.del(key). To delete items, say
del d[key].
len(s), min(s), max(s),
element in s, element not in s,
s1+s2 (concatenate), s*n (concatenate
n copies).
del s[i], del s[i:j],
s.index(item), s.reverse() (in place),
s.sort() (in place),
s.insert(position,item).
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() .
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]