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.
Let's create a 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:
We picked the general name
result here, but you can choose any name you deem appropriate. Always pick a name that best describes its contents. This practice makes your code more readable and easy to understand.
Variables are a crucial part of any programming 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:
These are all valid expressions because Python can evaluate them to a value:
# Evaluates to 9: 3 * 3 # Evaluates to 19 if result is 15: result + 4 # Simply evaluates to 2: 2
If you liked this page, please share it with a fellow learner: