Now that we can use Python as a calculator, wouldn’t it be nice to store the results of those calculations? For this, Python has the concept of a variable.
- A variable is used to store information that can be referenced later on.
Let’s create a Python variable called result. Before we do so, try and see if Python already knows what result is:
>>> result Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'result' is not defined
This is the way Python lets you know about errors. Ignore the first two lines and focus on the actual error instead. Python reports: name ‘result’ is not defined. So let’s define the name result as a variable and try this again:
>>> result = 3 * 5 >>> result 15
Step by step:
- Python sees a so-called assignment: we assign the result of 3 * 5 to the variable result.
- Next, we type in the result.
- Python does not recognize this as a command, so it tries to see if, perhaps, there’s a variable with this name. There is, and we assigned 15 to it. Hence this line evaluates to the number 15, which is printed to the screen.
We picked the general name
result here, but you can choose any name you deem appropriate. Always pick a variable name that best describes its contents. This practice makes your code more readable and easy to understand.
Python variables are a crucial part of the language because you can use them in other expressions too:
>>> 4 * result 60 >>> result - result 0 >>> _
I used the word expressions without explaining what an expression is, let’s fix that:
- An expression is anything that Python can evaluate to a value
These are all valid expressions because Python can evaluate them to a value:
# Evaluates to 9: 3 * 3 # Evaluates to 19 if the result is 15: result + 4 # Simply evaluates to 2: 2