In Section 3.2 we used variables for the
first time: a and b in the example. Variables are used
to store data; in simple terms they are much like variables in
algebra and, as mathematically-literate students, we hope you will
find the programming equivalent fairly intuitive.
Variables have names like a and b above, or x or
fred or z1. Where relevant you should give your
variables a descriptive name, such as firstname or
height 3.2.
Variable names must start with a letter and then may consist
only of alphanumeric characters (i.e. letters and numbers) and
the underscore character, ``_''. There are some reserved words which you
cannot use because Python uses them for other things; these are listed
in Appendix B.
We assign values to variables and then, whenever we refer to a variable later in the program, Python replaces its name with the value we assigned to it. This is best illustrated by a simple example:
>>> x = 5
>>> print x
5
You assign by putting the variable name on the left, followed by a
single =, followed by what is to be stored. To draw an analogy,
you can think of
variables as named boxes. What we have done above is to label a box
with an ``x'', and then put the number 5 in that box.
There are some differences between the syntax 3.3 of Python and normal
algebra which are important.
Assignment statements read right to left only. x =
5 is fine, but 5 = x doesn't make sense to Python, which will
report a SyntaxError. If you like, you can think of the equals sign as an
arrow pointing from the number on the right, to the variable name on the
left:
and read the expression as ``assign 5 to
x'' (or, if you prefer, as ``x becomes 5'').
However, we can still do many of things you might do in algebra, like:
>>> a = b = c = 0
Reading the above right to left we have: ``assign 0 to c,
assign c to b, assign b to a''.
>>> print a, b, c
0 0 0
There are also statements that are alegbraically nonsense, that are perfectly sensible to Python (and indeed to most other programming languages). The most common example is incrementing a variable:
>>> i = 2
>>> i = i + 1
>>> print i
3
The second line in this example is not possible in maths, but makes
sense in Python if you think of the equals as an arrow pointing from
right to left. To describe the statement in words: on the right-hand
side we have looked at what is in the box labelled i, added 1
to it, then stored the result back in the same box.
spam, lumberjack, and
shrubbery if you read up on Python on the web. As this is a
document written by deadly serious scientists we will avoid
this convention (mostly). However, it's something to be
aware of if you take your interest in Python further.