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:
- Variable
- 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 a calculation we make. In other words, we can assign the result of that calculation to a variable. We can create an unlimited number of variables; we just have to make sure we give them unique names.
Declaring a Python variable
We will 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
Code language: Python (python)
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 error messages will be a useful skill!
Now, let’s declare the variable name result
and try this again:
>>> result = 3 * 5
>>> result
15
Code language: Python (python)
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 thatresult
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.
Variable naming
In the example, we picked the general name result
, but you can choose any name you deem appropriate. Generally, 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 shopping_cart_total
.
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
>>> _
Code language: Python (python)
I used the word expressions without explaining what an expression is; let’s fix that:
- Expression
- 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
Code language: Python (python)
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.
Variable type
A value assigned to a variable does not have to be a number, by the way. Python has several data types besides numbers, which 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'>
Code language: Python (python)
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 almost time to learn more about Python strings, but there’s one last topic I want to discuss first.
Valid Python variable names
Some characters are not allowed 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:
- name_1
- name_2
- _database_connection
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:
- cartTotal
- carttotal
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 separate words more clearly.
We can use camel-case in Python, but we prefer underscores for variable names, while camel-case is the norm for class names. So instead of shoppingCartTotal
, we Pythonistas use shopping_cart_total
. However, we do use camel-case for class names, as you’ll soon learn.
Keep learning
So we’ve seen numbers and know how to store numbers in a variable. But what about text? Head over to the next section to learn all about Python strings.