27. Variables

Remember when we introduced synonyms? This was in the fifth lesson, when we said that you could make Reeborg learn to recognize other languages. The example we used was the French word for "move".

avance = move

Synonyms can be used for numbers too.

>>> n = 3
>>> print n
3
>>> 2*n
6
>>> n*n
9

Nice, isn't it? Now, we can change the value of a synonym as we need to.

>>> n = 3
>>> print n
3
>>> n = 2
>>> print n
2

Because the value of the synonym can change, we call it a variable. When you are creating a synonym, we say that you are assigning a value to a variable. The symbol used "=" should be read as "is a synonym for" instead of "is equal to" as you might be used to. This is because, if "n is equal to 2", then surely "2 is equal to n". Let's try to see what Python makes of this.

>>> n = 2    # this is ok
>>> 2 = n
SyntaxError: can't assign to literal

If a different symbol than the equal sign would have been available on standard keyboards, like

>>> n  3
>>> print n
3

it is very likely that Guido van Rossum, the inventor of Python, would have used it instead to mean "is a synonym for". However, it was not and we must use the equal sign instead. This also explains why we must use a double equal sign "==" when we want to test if two numbers are equal.

As we have seen briefly above, once a number is assigned to a variable, that variable can be used in the same way that we would use a number. For example:

>>> a = 1
>>> b = 2
>>> c = a + b
>>> print c
3

What we have just seen should be fairly easy to understand. The following might be a little bit more difficult at first glance:

>>> a = 1
>>> a = a + a   # Surprise?
>>> print a
2

You must remember that "=" should be read as "is a synonym for". So, the "surprising" line should be understood as follows:

Writing it all out like I did make it sound very complicated. In fact, you will quickly get used to it and very soon it will not surprise you at all.

Because this method for changing the value of a variable occurs so often, Python uses a "condensed" notation:

>>> a = 1
>>> a += 3       # same as "a = a + 3"
>>> print a
4

>>> a -= 2       # same as "a = a - 2"
>>> print a
2

>>> a *= 5       # same as "a = a * 5"
>>> print a
10

>>> a /= 2       # same as "a = a/2"
>>> print a
5

Your turn

Remember how difficult it was for Reeborg to add two numbers in base 10? Just to refresh your memory, we would like for Reeborg to be able to add two numbers in the following way:

3+2=5 3+2lead to 5

8+4=12 8+4lead to 12

You can use variables to make the task easier; when you do so, you don't need to have any special world, like we had to before, nor have Reeborg carry any beepers to start with. Here are a few suggestions:

previousInterpreting the Python keywords - home - Variables and functions next