In this Python tutorial, we will learn what variables are, how to declare a variable, how to assign values to variables, and how to read the values from variables.
Python Variables
In Python, a variable is a name that refers to a value. You use variables to store values such as numbers, text, lists, and results of calculations so that you can use them later in a program.
It is common to say that variables are containers for values. In Python, a more precise way to think about them is this: a variable name is bound to an object in memory. When you assign a new value to the same name, the name can refer to a different object.
Creating a Python Variable by Assignment
Assignment Operator = can be used to assign values to variables. Variable must be the left operand and the value assigned to it must be right operand. An example to assign a variable a with value 100 is given in the following.
a = 100
There is no explicit declaration required for a variable in Python, unlike in many other programming languages. When a variable is used in the python code, python interpreter automatically interprets the data type from the value assigned to the variable.
For example, the following statements create three variables. Python decides the type from the assigned value.
count = 10
price = 49.95
message = "Hello Python"
Python Variables Do Not Need a Declared Data Type
Python is dynamically typed. This means the type is associated with the value at runtime, not permanently fixed to the variable name. The same variable name can refer to an integer first and a string later.
x = 25
print(type(x))
x = "Python"
print(type(x))
Output
<class 'int'>
<class 'str'>
This flexibility is useful, but it also means that you should choose clear variable names and avoid reusing the same name for unrelated values in the same part of a program.
Reading Values from Python Variables
To read the value stored in a variable, the variable has to be given on the righthand side of the assignment operator, or in an expression, etc.
In the following example, we take two variables a and b and assign them with integer values. We try to add the values stored in these two variables. We read the values from variables by including them in an expression, which in this case is a + b.
While Python interprets this code, a and b are substituted with the values stored in them.
Example.py
a = 10
b = 20
total = a + b
print(total)
Output
30
You can use variables in calculations, function calls, comparisons, loops, and conditional statements. A variable must be assigned a value before you read it. Otherwise, Python raises a NameError.
total = marks + 10
print(total)
Output
NameError: name 'marks' is not defined
Python Variable Naming Rules
A Python variable name must follow a few rules. A valid variable name can contain letters, digits, and underscores, but it cannot start with a digit. Variable names are case-sensitive, so total, Total, and TOTAL are three different names.
- Use names such as
student_name,total_marks, andis_validfor readable Python code. - Do not use spaces or special characters such as
@,-, or#in variable names. - Do not use Python keywords such as
for,if,class, orreturnas variable names. - Prefer lowercase words separated by underscores for normal variable names.
student_name = "Arun"
total_marks = 92
is_passed = True
The following names are not valid Python variable names.
2total = 50
student-name = "Arun"
class = "Python"
Common Data Types Stored in Python Variables
A Python variable can refer to values of many data types. The most common beginner-level examples are integers, floating-point numbers, strings, booleans, lists, tuples, dictionaries, and sets.
| Value assigned to variable | Python data type | Example |
|---|---|---|
| Whole number | int | age = 18 |
| Decimal number | float | price = 99.5 |
| Text | str | name = "Ravi" |
| True or false value | bool | is_active = True |
| Ordered, changeable collection | list | marks = [80, 85, 90] |
| Key-value collection | dict | student = {"name": "Ravi"} |
You can check the type of a value using the built-in type() function.
name = "Ravi"
age = 18
marks = [80, 85, 90]
print(type(name))
print(type(age))
print(type(marks))
Output
<class 'str'>
<class 'int'>
<class 'list'>
Assigning Multiple Python Variables in a Single Line
In Python, we can assign multiple variables a value in a single statement.
In the following program, we take variables for months and assign values of 31 for months with 31 days, 30 for months with 30 days, and 28 for feb. We assign all the months with 31 days in a single statement. Similarly for months with 30 days.
Example.py
jan = mar = may = jul = aug = oct = dec = 31
apr = jun = sep = nov = 30
feb = 28
total = jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec
print(total)
Output
365
You can also assign different values to different variables in one statement. The number of variables on the left should match the number of values on the right.
name, age, city = "Ravi", 18, "Hyderabad"
print(name)
print(age)
print(city)
Output
Ravi
18
Hyderabad
Updating the Value of a Python Variable
After a variable is created, you can update it by assigning a new value to the same name. The old binding is replaced by the new one.
score = 50
print(score)
score = score + 10
print(score)
Output
50
60
The expression score = score + 10 reads the current value of score, adds 10, and assigns the result back to score.
Variables Referring to the Same Python Object
More than one variable name can refer to the same object. This matters especially when the object is mutable, such as a list or dictionary.
numbers = [10, 20, 30]
same_numbers = numbers
same_numbers.append(40)
print(numbers)
print(same_numbers)
Output
[10, 20, 30, 40]
[10, 20, 30, 40]
Both names refer to the same list object in this example. When the list is changed through same_numbers, the change is visible through numbers too.
Constants in Python Programs
Python does not have a built-in constant keyword for normal variables. By convention, programmers write constant-like names in uppercase letters to show that the value should not be changed.
PI = 3.14159
MAX_USERS = 100
DEFAULT_LANGUAGE = "English"
This is a naming convention, not a strict rule enforced by Python. A program can still assign a new value to PI, but it should not do so if the name is being used as a constant.
Common Mistakes with Python Variables
- Using a variable before assigning it: assign a value before reading the variable.
- Mixing uppercase and lowercase names:
marksandMarksare different variables. - Choosing unclear names: prefer
total_priceover names such asxwhen the meaning is important. - Using invalid characters: use underscores instead of hyphens or spaces.
- Assuming the variable has a fixed type: the name can be rebound to a value of another type.
Quick Practice on Python Variables
Try to predict the output before looking at the answer.
item = "Book"
price = 120
quantity = 3
total_price = price * quantity
print(item)
print(total_price)
Output
Book
360
Python Variables Editorial QA Checklist
- Does the tutorial explain that Python variables are names bound to values, not fixed typed containers?
- Are all Python variable examples runnable without missing definitions, except the intentional
NameErrorexample? - Are variable naming rules shown with both valid and invalid examples?
- Are output blocks clearly separated from Python code blocks?
- Does the explanation distinguish assignment, reading a value, updating a value, and multiple assignment?
Frequently Asked Questions on Python Variables
What are variables in Python used for?
Variables in Python are used to give names to values. They help you store data, reuse values, calculate results, pass data to functions, and make programs easier to read.
Do Python variables need declaration before use?
No. Python variables do not need a separate declaration statement. A variable is created when you assign a value to a name, such as total = 100.
What data types can Python variables hold?
Python variables can hold values such as integers, floats, strings, booleans, lists, tuples, sets, dictionaries, and objects. The variable name can later be assigned a value of another type.
What are the main types of variables in Python?
In beginner Python, variables are often discussed by the kind of value they refer to, such as numeric variables, string variables, boolean variables, and collection variables. In object-oriented Python, you may also see local variables, global variables, instance variables, and class variables.
Why do two Python variables show the same list after one is changed?
If two variable names refer to the same mutable object, such as a list, changing the object through one name is visible through the other name. To create a separate list, make a copy instead of assigning the same list directly.
Python Variables Summary
In this Python Tutorial, we learned about variables in Python: how assignment creates a variable name, how to read and update values, how multiple assignment works, how Python handles data types dynamically, and which naming rules help keep Python code readable.
TutorialKart.com