Getting started
Basic concepts: taking our first steps
Using an IDE
Objects and classes
Loops, ranges, and iterators
Working with files
Exception handling
Python data types
Course project: building a TODO application
And now what?

Defining variables

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.

What is a Python variable?

Let’s start by defining more formally what a variable is:

Variable
A variable is a named piece of computer memory, used to store information that can be referenced later on.

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.

Declaring a Python variable

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:

  • Python sees a so-called assignment: we assign the result of 3 * 5 to the variable called 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.
  • Next, we type 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 on the screen.

Creating more variables

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