The Rules
For a full treatment of the rules of
Python, see the Python Language Reference, which is available
online with BlackAdder and Python. This section will in a series
of short statements enumerate what makes Python Python.
Objects and references
Before Python 2.2, not all types were
classes, but now they are.
Moore's law has made type declarations
obsolete (with thanks to Paul Prescod).
An object has a type (which you can
query with type()). A reference does not
have a type. You can use the same name to refer to two objects
in succession, but the first reference disappears as soon as
you've made the second.
Objects disappear once the last
reference has gone (except if the reference is an explicit
weak reference). You can destroy a reference with
del — from that moment on, the name
doesn't exist anymore. If you set the reference to
None, the link to the object disappears,
but the reference remains in existence.
>>> a="aaa"
>>> print a
aaa
>>> del a
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'a' is not defined
>>> a="aaa"
>>> print a
aaa
>>> a=None
>>> print a
None
>>>
Functions and classes are both also
objects.
Every object has one identity, which
you can retrieve with id():
>>> a=A()
>>> id(a)
135121324
Some types are callable (i.e., put on a
line with an argument list between ()) and can return a value.
Callable types include classes, methods in clasess, functions
and objects that implement the special method
__call__.
Formatting
A block is first marked by a colon at
the end of the previous line, and is indented. The block ends
at the next dedent. (You should indent with four spaces, and
not use tabs.)
Whatever is typed between brackets is
considered to be on one line. Dictionaries are delimited with
curlies {}, lists are delimited with brackets [] and tuples
(and lists of arguments to functions) are delimited with
().
A classname should start with a capital
letter; variable and function names should begin with a
lowercase letter.
Only alphabetic characters (a-z, A-Z),
digits (0-9) and the underscore (_) are valid in variable
names, but a variable name should not start with a
digit.
Names that start with one underscore (_)
are a bit private (not imported with from module
import *); names that start with two underscores
(__) are very private in scope (not visible with
dir(object)); names that start and end
with two underscores are system-defined.
Python 2.1.1 (#1, Aug 11 2001, 20:14:53)
[GCC 2.95.2 19991024 (release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> class A:
... def __test():
... pass
...
>>> dir(A)
['_A__test', '__doc__', '__module__']
>>> a=A()
>>> dir (a)
[]
Keywords
The following keywords are reserved:
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Literals
Strings can be enclosed in single (' or
") or triple (''' or """") quotes. Triple-quoted strings can
span lines, the linebreaks are part of the string. If you
prefix the string literal with u, it becomes a Unicode
string.
Numbers can be integers, long integers,
floating point, and imaginary. If you divide integers or long
integers, you will not get a float, but the integer before the
decimal symbol (unless you import division from
future in Python 2.2).
Python has the following operators:
+ — * ** / %
<< >> & | ^ ~
< > <= >= == != <>
The comparison operators
<> and != are
alternate spellings of the same operator.
!= is the preferred spelling;
<> is obsolescent.
Methods and functions
Functions are callable objects that
return a value (if a function doesn't explicitly return a
value, it retuns None). Methods are the
same, but part of a class. A method's argument list always has
self (which refers to the class instance)
as its first argument.
A function can be called with positional
arguments, or named arguments. When mixed, positional
arguments come first.
A variable number of positional
arguments is indicated by *args, and a
variable number of named arguments is indicated by
**args. You can access
*args as a tuple in your function, and
**args as a dictionary in your
function.
>>> def f(a):
... print a
...
>>> def ff(a, b):
... print a, b
...
>>> def fff(*args):
... print args
...
>>> def ffff(**args):
... print args
...
>>> f(1)
1
>>> ff(1, b=2)
1 2
>>> fff(1,2,3)
(1, 2, 3)
>>> ffff(a=1,b=2,c=3)
{'b': 2, 'c': 3, 'a': 1}
>>>
High level datatypes
Python has three very high level
datatypes: tuples, lists and dictionaries.
A tuple is any combination of unique
objects. You can't change the composition of items in a tuple
(i.e. substitute another object), although the objects
themselves can be changed.
>>> t=("a","b","c")
>>> t
('a', 'b', 'c')
>>> t[2]="d"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>>
A list is a list of objects. You can
change which objects are in a list, adding and deleting items
to your heart's delight.
>>> l=["a", "b", "c"]
>>> l[2]="d"
>>> l
['a', 'b', 'd']
>>>
A dictiony is a keyed list. Keys, which
must be unchangeable (i.e. not lists) point to values. One
key, one value. There can be no duplicate keys in a
dictionary.
>>> d={"a": "aaa", "b": "bbb", "c": "ccc"}
>>> d
{'b': 'bbb', 'c': 'ccc', 'a': 'aaa'}
>>> d[2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 2
>>> d["b"]
'bbb'
>>> d["b"]="ddd"
>>> d
{'b': 'ddd', 'c': 'ccc', 'a': 'aaa'}
>>>