In the previous section, we used Python as a calculator by leveraging the REPL. Wouldn’t it be nice to store the results of those calculations? For this, we use the Python variable. In this article, you learn what a variable is and how to declare one. We’ll also look at the rules and best practices for creating variables.
Table of contents
What is a Python variable?
Let’s start by defining more formally what a variable is:
- A variable is used to store information that can be referenced later on.
So a variable is what we use to name 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.
Declaring a Python variable
We can create a Python 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 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: result is 3 times 5.
- Next, we type
- 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.
In the example, we picked the general name
result, but you can choose any name you deem appropriate. As a general rule, always pick a variable name that best describes its contents. This practice makes your code more readable and easy to understand. If we were calculating the total price of a shopping cart here, for example, a good name would be
Don’t skimp on the number of characters in your variable names. It’s better to have clean, readable names like
shopping_cart_total instead of an abbreviation like
sct. As you’ll soon learn, a good code editor auto-completes things like variable names, so you don’t have to type them in completely, if that’s what you’re worried about.
Using variables in expressions
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
What you see above the expressions, are called comments. Anything that follows a hash symbol (the #) is seen as a Python comment and ignored by the Python interpreter.
A value assigned to a variable does not have to be a number, by the way. Python has several data types besides numbers, and they can all be the result (the value) of an expression. One such data type is the Python string, which is, uncoincidentally, the topic of the next article in the tutorial! But there are others too, like booleans and tuples.
Python has a built-in function called
type(), which we can use to determine a variable or expression type. Here are some examples:
>>> my_number = 4 >>> type(my_number) <class 'int'> >>> my_string = 'Hello' >>> type(my_string) <class 'str'>
First, we created a variable with the value 4. When asked, Python tells us this variable is of class int, which is short for integer. Follow the link for a more thorough explanation of integers, if you like.
Next, we create a string. And when asked, Python indeed tells us that it is of class str, short for string. It’s now time to learn more about Python strings.
Valid Python variable names
You can’t use all characters in a variable name; there are a few rules we need to abide by. Let’s start with the complete list of valid characters that can appear in a variable name:
- Lowercase and uppercase letters: a-z and A-Z
- Numbers: 0-9
- Underscores: _
Additionally, there are these two rules:
- Variable names must start with a letter or the underscore character, and can not start with a number.
- Names are case-sensitive
Here are some valid variable names:
These are invalid names:
- 1tomany (don’t start with a number)
- my-number (- is not allowed)
- my number (spaces are not allowed)
And these variables are not the same, due to case sensitivity:
A note on camel-case
This is for those that come from another programming language, like C# or Java. Many programming languages make use of camel-case to name variables. With camel-case, we use uppercase letters to more clearly separate words.
In Python, we can use camel-case, but we prefer underscores for variable names, while camel-case is the norm for class names. So instead of
shoppingCartTotal, we Pythonistas use
So we’ve seen numbers, and we know how to store numbers in a variable. But what about text? Head over to the next section to learn all about Python strings.