In the previous section, we used Python as a calculator. But as I mentioned, it would be nice to store the results of those calculations. For this, we use variables. In this topic, you learn what a variable is and how to declare and use one. We’ll also look at the rules and best practices for creating variables.
Let’s start by defining more formally what a variable is:
So a variable is what we use to name and store the result of, for example, a calculation we make. Or, in other words, we can assign the result of that calculation to a variable. We can create an unlimited amount of variables; we just have to make sure we give them unique names. If it helps, you can also see a variable as a named container that holds a value for us.
We will create a variable (formally called declaring a variable) called result
in the REPL. But before we do so, we’ll 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 for now and focus on the actual error instead. Python reports: name 'result' is not defined
. Python errors tend to be very helpful if you know where to look. That’s why I wanted to show you one. Eventually, you’ll need to write code on your own, and running into errors is, unfortunately, a big part of the job. Being able to decipher errors will be a useful skill!
Now let’s declare the variable name result
and try this again:
>>> result = 3 * 5 >>> result 15
Step by step this is what happens:
result
. Assignments are done with the ‘=’ character, which is conveniently called ‘is’. So we just told Python: I declare that result
is the result of the expression 3 * 5.result
.Now it’s your time to shine. Create another variable, with another name. Assign anything you want to it! In fact, you can even assign result
to your new variable.
Here’s are some ideas in case you need it:
>>> result = 3 * 15 >>> my_copy = result >>> another_var = 1 + 3 + 5