In Python, you can store values to variables.
The value of a variable can then be changed throughout the execution of the program.
For example, let’s create a bunch of variables:
x = 10 name = "Alice" age = 58
As you can imagine, storing data is essential to a computer program.
For instance, a typical game application keeps track of some kind of score. Behind the scenes, the score is a variable that is updated based on certain actions.
This is a comprehensive guide on variables in Python. You are going to learn important concepts, such as:
- Variable Assignment
- Variable Types
- References and Identity
- Naming conventions
All the theory is backed up by great examples.
To create a variable in Python:
- Come up with a name for the variable.
- Use the assignment operator (=) to give it a value.
For example, let’s create a variable called name and assign the name “Alice” to it:
name = "Alice"
Once you have created a variable in your program, you can use it. This is the whole point of variables in Python.
For example, let’s display the value of the variable name:
Now you can also change the value of the name variable.
For instance, let’s turn the name into Bob:
name = "Bob" print(name)
As you can see, now the name is no longer Alice. Instead, it was changed to Bob. It will remain Bob until you change it again.
In this example, you learned how to create variables with the assignment operator.
Sometimes when you create multiple variables all with the same value, you introduce unnecessary repetition in your code.
To fix this, Python supports what is called a chained assignment.
A chained assignment allows you to assign the same value to multiple variables in a single expression.
To demonstrate this, let’s create three variables on separate lines:
x = 0.0 y = 0.0 z = 0.0
However, because the value of each variable is the same, you could have used a chained assignment like this:
x = y = z = 0.0
Let’s print these variables to see that they are indeed 0.0 each:
print(x, y, z)
0.0 0.0 0.0
Now you understand the basics of variables in Python.
Next, let’s talk about the types of variables there are in Python.
Variables Types in Python
Variables are by no means a Python-only concept. Instead, variables are broadly used in each and every programming language as one of the building blocks of code.
In many other programming languages, variables are statically typed.
This means a variable is restricted to a single data type. In other words, no value of a different data type can be assigned to it.
As an example, if you declare an integer variable, you cannot assign a string to it.
This is what is meant by static typing.
However, Python does not have this restriction!
In Python, variables are dynamically typed.
In other words, the data type of a variable is open to change.
For example, let’s create an integer variable and turn it into a string on the next line:
x = 10 x = "Test" print(x)
As you can see, this change of data type causes no problems in Python.
In some other languages, doing this kind of change would cause errors in your code.
In Python, every single object is automatically associated with a unique identifier number, or ID for short.
In a Python program, it is guaranteed there can be no two objects with the same ID.
Occasionally, it can be useful to be able to check the ID of the object.
To do this, use the id() function.
For example, let’s store two integer objects into variables and check their identity:
a = 10 b = 20 print(id(a)) print(id(b))
As you can see, the two IDs are different.
In other words, the integer objects 10 and 20 are stored in different memory addresses.
Although this is a beginner-friendly guide, we need to take a behind-the-scenes look at variable assignments to truly understand what happens.
This is important to understand right off the get-go because:
- It causes strange behavior if you do not know how it works.
- It works differently in some common programming languages.
Objects in Python
In the previous chapter, you already heard the word “object”.
But what is an object? Is it the same as a variable?
Python is an object-oriented programming language. This means practically everything in Python is an object.
You are going to hear this a lot.
But what does it mean?
Consider this piece of code:
Apparently, this displays the number 1000 in the console.
But behind the scenes, there is a lot more going on.
When you run this piece of code, the Python interpreter:
- Creates an integer object to the memory.
- Assigns a value of 1000 to the object.
- Displays the value of the object in the console.
How about when we assign a value to a variable?
In Python, a variable is just a symbolic name for an object behind the scenes.
When you assign an object to a variable, you use the variable as a reference to the object somewhere in memory.
In other words, the variable itself is not an object. Instead, it is a pointer to an object.
All of this probably sounds confusing to you. Let’s see an example with an illustration to help to understand it better.
For instance, let’s create a variable x and assign 1000 to it:
x = 1000
Behind the scenes:
- An integer object is created with a value of 1000. This object is stored somewhere in the memory.
- In addition, a variable x is created to reference the integer object. The x acts as a middleman between you and the actual object in memory. Without x you could not access the integer object.
Here is an illustration of the situation:
But here is where it gets interesting.
Consider creating another variable y where you assign the variable x.
y = x
This does not copy the value of x to a y! Instead, it creates a new symbolic name for the same object the variable x points to.
Here is a behind-the-scenes look at the situation:
To verify these variables refer to the same object, let’s see their identities using the id() function:
As you can see, the IDs match.
In other words, the variables x and y are both aliases to the same object in memory.
But now, let’s assign a new value to one of the variables:
y = 5000
This creates a new integer object somewhere else in the memory and makes y point to it.
If you print the identities of the variables x and y again, you can see that now they reference different objects in memory:
As expected, the IDs were different.
To take home, Python variable assignment means creating a reference to an object in the memory. The variable itself is not an object. Instead, it is a name via which the object can be accessed.
Notice that in Python tutorials, variables are often called objects for short. However, they are still only references to the objects. If someone says “x is an integer object” they mean “x is a variable that refers to an integer object in memory”.
Thus far you have mostly used short variable names such as x or y.
But variable names can and usually should be longer than that.
In this part, you learn how to create descriptive and valid variable names in Python.
Why Does Variable Naming Matter?
Understanding code is a brain-heavy task.
As a programmer, your task is always to write understandable code.
This is beneficial to yourself and your teammates or project members.
Writing clean and understandable code starts with variable naming.
When it comes to variable naming, you need to be descriptive. The variables should not be cryptic. Instead, the variable names should express themselves.
Before talking about the best naming conventions of Python variables, let’s briefly discuss the restrictions and rules.
Variable Naming Rules and Restrictions
In Python, a variable name can:
- Contain as many characters as you want.
- Consist of both lowercase and uppercase letters.
- Consist of digits.
- Contain the underscore (_).
In Python, a variable cannot:
- Start with a digit.
- Contain special characters (except for underscore).
- Be a reserved keyword.
Here are some valid and invalid variable name examples:
# Valid names x = 10 VERSION10 = "test" distance_to_house = 100.00 # Invalid names 5_letters = "Hello" my name = "Artturi" first&second = "Alice, Bob" for = "test"
With the variable naming rules out of the way, let’s talk about the naming conventions.
Variable Naming Conventions
There are many different blueprints for naming variables in Python.
There is not a single agreed way to name variables.
But there is a bunch of naming conventions that are commonly used.
In this part, you are going to see a couple of commonly used naming conventions in Python.
When it comes to variable naming, the most important part is to be clear and descriptive with the name of the variable.
When your variables are self-descriptive, you or one of your teammates can understand the code easily. This makes it easier to manage and build on top of the existing code.
Do not be afraid to use longer names and combinations of different words if needed.
For example, here is a great example of a descriptive variable naming:
distanceToHouse = 100.00
And here is a really bad example:
dth = 100.00
It is easy to understand the first variable. On the other hand, it is impossible to understand what the second variable is without context.
This is a great example of a long variable name that does its job really well.
When you need to combine multiple words in a variable name, there are many ways to do it.
For example, these all are valid variable names in Python:
distancetohouse = 100.00 DISTANCETOHOUSE = 100.00 distanceToHouse = 100.00 DistanceToHouse = 100.00 distance_to_house = 100.00
But for some of these names, there is room for improvement.
For example, take a look at the first two names:
distancetohouse = 100.00 DISTANCETOHOUSE = 100.00
Because you cannot use a space in a variable name, the consecutive words are not visually separated.
To “separate” the multiple words in a variable name, there are a bunch of commonly used conventions.
- Camel Case. Starting from the second word, every consecutive word starts with a capital letter.
- For example, distanceToHouse
- Pascal Case. Each separate word starts with a capital letter, including the first one.
- For example, DistanceToHouse
- Snake Case. Words are separated by underscores.
- For example, distance_to_house
In Python, you commonly see the 1st or 3rd approach being used with variable names.
At the end of the day, naming conventions boil down to personal preference.
In the Python community, there is no single naming convention that everyone would follow.
Thus, you should stick with one that is visually most appealing to you. At least do not use different naming conventions in the same project.
At some point, you should also read the Style Guide for Python to learn more. However, when you are learning about variables in Python, it is too early to worry too much about conventions.
Read next: Operators in Python
In this guide, you learned how to use variables in Python.
To recap, every computer program needs to be able to store values so that it can use/modify them later.
In Python, you can store values to variables.
For example, let’s create a variable that holds a number:
x = 10
Behind the scenes, a variable is a symbolic name that points to an object somewhere in the memory. In other words, the variable itself is not the object but rather the “key” to it.
When you give a name to a variable, be specific. A good variable name reveals what the variable is about. This in turn makes the code easier to read and manage. Do not be afraid to use names that combine multiple words.
For instance, here is a good variable name:
distanceToHome = 100.00
Read next: Operators in Python
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.01.10How to Use AI Art Generators—Input Design (Prompt Engineering)
- Favorites2022.11.30ChatGPT—What Is It? How to Use It? (Examples, Tips & More)