Python Variables & Constants Tutorial
In this tutorial we learn how to create and use mutable data containers, called variables, to store our application's temporary data.
We also learn how to create and use immutable containers, called constants, when we don't want our values to be changed at runtime.
Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)
- What are variables and constants?
- Boolean & Special literals
Let's jump right in.
What are variables and constants?
Variables and Constants are two of the temporary data containers that store data used by the application while it runs.
When we start an application, space is allocated in memory (RAM) to store the data from the data containers. When the application quits, or the data is no longer used by the program, the garbage collector will collect and discard it, freeing up the space in memory that it used.
Technically, the data containers in Python are objects, we don’t really assign values to them. Instead, Python returns the object to the data container.
We will cover objects in the lessons about classes, so you don’t have to understand or worry about it at this point.
A variable is a simple container that makes it easy for us to refer to temporarily stored data at a later stage. It’s mutable, which means that we may change the data inside the variable at runtime.
How to declare / initialize a variable
Unlike many other languages, such as C++, variables aren’t explicitly declared. A declaration happens automatically when we assign a value to a variable, otherwise known as initialization.
To initialize a variable in Python we use a name, followed by the equals operator = and a value.
variable_name = value
message = "Hello World" print(message)
This process may seem redundant. Why store the message in a variable and then print the variable, isn’t it extra typing? Well yes, but if our data is stored somewhere, the application can control and manipulate the data when it runs.
The assignment operator ( = )
We have seen the assignment operator and L&R values before, but let’s quickly go through it again.
The assignment operator tells the interpreter to assign whatever the Rvalue (on the right) is, into whatever the Lvalue (on the left) is.
Lvalue = Rvalue
The statement reads: Lvalue holds Rvalue
How to change the value of a variable
As mentioned earlier in this lesson, variables are mutable, which means their values can be changed at runtime. Changing the value of a variable is as simple as assigning a new value to it.
message = "Hello World" print(message) # change value message = "Hello there" print(message)
In the example above, the new value overwrites the old value.
How to assign a single value to multiple variables
Python allows us to assign a single value to multiple variables inline. To do this, we specify the names of our variables, separated by = and followed by the value that we want to assign to all of them.
variable_1 = variable_2 = variable_3 = value
The statement reads: "variable_1" holds the value of "variable_2", which holds the value of "variable_3" which holds value.
a = b = c = 1 print(a) print(b) print(c)
In the example above, we initialize the variables a, b and c with the value 1.
How to assign multiple values to corresponding variables inline
Python also allows us to use an inline, shorthand method to assign multiple values to multiple variables.
First, we specify our variable names separated with the comma operator. Then, we use the assignment operator. Lastly, we specify our values, also separated by the comma operator.
# inline assignment variable_name_1, variable_name_2 = value_1, value_2 # regular assignment variable_name_1 = value_1 variable_name_2 = value_2
name, age = "John", 30 print(name) print(age)
In the example above we assign the name “John” to the variable name and the number “30” to the age variable.
We should take care with multiple assignment to assign the correct value to its corresponding variable.
A constant is a data container similar to a variable except that it is immutable. That means once the application runs, the value of a constant cannot be changed.
Constants are used when we have data that shouldn’t change, like the value of Pi.
In Python, constants are usually initialized in a module. For now, to keep things simple, we will initialize our constants in the same file as our other code.
How to declare / initialize a constant
A constant is initialized exactly like a variable. Again, we use a name, the assignment operator and a value.
The only change in syntax for a constant is the convention of naming constants in all uppercase letters, separating words with underscores.
PI = 3.14
In reality constants don’t exist in Python, their values can be changed. Instead, programmers rely on conventions, such as uppercase naming, to state that the value is supposed to be constant and should not be changed.
Constants are also usually separated into a constants module to minimize the risk of changing the value at runtime.
Boolean & Special literals
A literal is raw data that is given in a variable or constant. Python has various types of literals, in this lesson we will learn about Boolean and Special literals.
A boolean literal can only ever have one of two values, True or False. Booleans are usually used in conditional checks that control the flow of the program, like if statements or while loops.
age = 18 may_vote = False if age == 18: may_vote = True print("Lie detector, I am old enough to vote\nCalculating...\n", may_vote)
In many languages, including Python, booleans represent a numerical value of 1 or 0. True represents 1, and False represents 0.
The True and False keywords are there to make the code more readable and user-friendly.
Booleans are two of the three keywords in Python that are spelled with the first letter in uppercase. If wedon’t remember to capitalize booleans, the interpreter will raise an error.
Special literals, None
We can think of None as a missing piece of information, the absence of a value. Maybe a value that isn’t there yet, but will be in the future.
To initialize a None value, we simply assign None as a value to a variable.
# before registration, username exists # but doesn't have a value, because # a user has not registered yet username = None print("User:", username) # when the user registers, they choose # a username and the variable can be # filled with a value username = "MorpheusCoolDude101" print("User:", username)
In the example above, the username variable exists to hold the user’s name when they register. Until a user registers we need a placeholder, something that is not a value but will not raise an error.
None is often compared to null from other languages, but we can’t really, because not all language nulls mean the same thing.
Some nulls, like in C#, mean “unknown value” or “absence of value” which is different from a null that means “no value” or “uninitialized variable”.
Summary: Points to remember
- A variable is a data container to store data temporarily while an application runs.
- A variable is not declared but initialized when a value is assigned to it.
- A variable is mutable, its values may be changed at runtime.
- We can assign one value to multiple variables by assigning them to each other in a row.
- We can assign values to corresponding variables in a row by separating them with a comma.
- A constant is a data container to store data that should not change at runtime.
- Constant data can technically be changed but we follow conventions to reduce the risk of it happening.
- Constants are, by convention, named in ALL_CAPS with an underscore separating words.
- Constants are, by convention, stored in modules.
- Booleans are literals that represent a positive or negative state.
- Booleans can only ever be True or False.
- Booleans represent numeric values. True represents 1 and False represents 0.
- None is a literal that represents the absence of a value.
- None can be used as a placeholder for code that does not exist yet.