Game Development Reference
In-Depth Information
2 - The Interactive Shell
The first time you store a value inside a variable by using an assignment statement,
Python will create that variable. Each time after that, an assignment statement will only
replace the value stored in the variable.
Now let's see if we've created our variable properly. If we type
spam
into the shell by
itself, we should see what value is stored inside the variable
spam
.
>>> spam = 15
>>> spam
15
>>>
Now,
spam
evaluates to the value inside the variable, 15.
And here's an interesting twist. If we now enter
spam + 5
into the shell, we get the
integer
20
, like so.
>>> spam = 15
>>> spam + 5
20
>>>
That may seem odd but it makes sense when we remember that we set the value of spam
to
15
. Because we've set the value of the variable
spam
to
15
, writing
spam + 5
is like
writing the expression
15 + 5
.
If you try to use a variable before it has been created, Python will give you an error
because no such variable would exist yet. This also happens if you mistype the name of the
variable.
We can change the value stored in a variable by entering another assignment statement.
For example, try the following:
>>> spam = 15
>>> spam + 5
20
>>> spam = 3
>>> spam + 5
8
>>>
The first time we enter
spam + 5
, the expression evaluates to
20
, because we stored