|
| Home |
|---|
Python variables are names used to refer to values and objects in a Python program. Variables allow programs to work with information such as numbers, text, Boolean values, lists and dictionaries without having to write the actual values repeatedly.
Variables are one of the most important concepts in Python programming. Almost every Python program uses variables to store information, perform calculations, process user input and keep track of data while the program runs.
Python makes variables particularly easy to create because you do not need to declare the data type before assigning a value. Python automatically determines the type of the object assigned to a variable.
In this tutorial, you will learn what Python variables are, how to create and assign variables, how to change variable values, Python variable naming rules, multiple assignment, type checking, dynamic typing, constants, variable scope and common mistakes beginners should avoid.
A Python variable is a name that refers to an object. When you assign a value to a variable, Python creates or uses an object representing that value and associates the variable name with it.
For example:
age = 25
print(age)
25
In this example, age is the variable name and
25 is the value assigned to it.
A simple way for beginners to think about a variable is as a label attached to a value. The variable name allows the program to refer to that value later.
Creating a variable in Python is simple. You create a variable by assigning
a value to a name using the assignment operator =.
The basic syntax is:
variable_name = value
For example:
name = "Alice"
age = 25
city = "London"
Three variables have been created:
name refers to the string "Alice".age refers to the integer 25.city refers to the string "London".
The process of giving a value to a variable is called
variable assignment. Python uses the
= operator for assignment.
score = 85
print(score)
85
The assignment statement tells Python that the name
score should refer to the value 85.
It is important to remember that = means assignment in
Python. It does not mean mathematical equality.
Once a variable has been created, you can use its name whenever you need to access the value.
price = 50
quantity = 3
total = price * quantity
print(total)
150
Here, the variables price and quantity are used
in a calculation. The result is then assigned to another variable called
total.
This is one of the main advantages of variables: programs can work with data without repeatedly writing the original values.
Python variables can refer to objects of many different data types. Common examples include integers, floating-point numbers, strings, Boolean values, lists and dictionaries.
name = "Alice"
age = 25
height = 5.6
is_student = True
print(name)
print(age)
print(height)
print(is_student)
Alice
25
5.6
True
In this example:
name refers to a str.age refers to an int.height refers to a float.is_student refers to a bool.
Python provides the built-in type() function to determine
the type of object referred to by a variable.
age = 25
print(type(age))
<class 'int'>
You can check several variables in the same program.
name = "Alice"
age = 25
height = 5.6
is_student = True
print(type(name))
print(type(age))
print(type(height))
print(type(is_student))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
Python is a dynamically typed language. This means you do not normally specify a variable's data type when creating it. Python determines the type from the object assigned to the variable.
For example, you can assign an integer to a variable without declaring it as an integer.
age = 25
print(type(age))
You can later assign a string to the same variable name:
value = 25
print(type(value))
value = "Python"
print(type(value))
<class 'int'>
<class 'str'>
The name value first refers to an integer object and later
refers to a string object. This flexibility is an important feature of
Python.
A variable can be assigned a new value during program execution.
age = 25
print(age)
age = 30
print(age)
25
30
The name age first refers to the value 25.
After the second assignment, it refers to 30.
Variables are often updated using their current value. This is useful for counters, totals and calculations.
score = 50
score = score + 10
print(score)
60
Python first evaluates score + 10 and then assigns the
result back to score.
Python provides shorthand assignment operators that make it easier to update variables.
| Operator | Example | Equivalent To |
|---|---|---|
= |
x = 10 |
Assign 10 to x |
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
//= |
x //= 5 |
x = x // 5 |
%= |
x %= 5 |
x = x % 5 |
**= |
x **= 2 |
x = x ** 2 |
score = 50
score += 10
print(score)
60
The statement score += 10 adds 10 to the existing value of
score.
Python variable names must follow certain rules. Following these rules prevents syntax errors and makes programs easier to understand.
The following are examples of valid Python variable names:
name = "Alice"
_age = 25
student1 = "John"
student_name = "Mary"
total_marks = 95
These names follow Python's variable naming rules.
Some names cannot be used as Python variables because they violate the language's naming rules.
1name = "Alice"
student-name = "John"
student name = "Mary"
These examples are invalid because:
1name starts with a number.student-name contains a hyphen.student name contains a space.A better approach is to use underscores to separate words.
student_name = "Mary"
Python treats uppercase and lowercase letters as different. Therefore,
name, Name and NAME can refer to
different variables.
name = "Alice"
Name = "Bob"
NAME = "Charlie"
print(name)
print(Name)
print(NAME)
Alice
Bob
Charlie
For this reason, it is important to use consistent capitalization when writing Python programs.
Although Python allows many technically valid names, programmers normally follow naming conventions to make code easier to read.
The most common convention for ordinary Python variables is snake_case. Multiple words are separated using underscores.
first_name = "Alice"
student_age = 20
total_marks = 450
average_score = 90.0
Names such as student_age and
average_score are easier to read than names such as
studentage or averagescore.
Python has reserved words called keywords. These words have special meanings in Python syntax and cannot normally be used as variable names.
For example, if, for, while,
class and return are Python keywords.
This is invalid:
if = 10
Instead, choose another descriptive name such as:
condition = 10
Python allows multiple variables to be assigned values in a single statement.
name, age, city = "Alice", 25, "London"
print(name)
print(age)
print(city)
Alice
25
London
The values are assigned from left to right to the corresponding variable names.
Python also allows the same value to be assigned to several variables at once.
x = y = z = 0
print(x)
print(y)
print(z)
0
0
0
This can be useful when several variables need the same initial value.
Python provides a convenient way to exchange the values of two variables without requiring a temporary variable.
a = 10
b = 20
a, b = b, a
print(a)
print(b)
20
10
This is a useful and commonly demonstrated feature of Python variable assignment.
Variables are frequently used to store information entered by users.
The input() function receives user input and the result can
be assigned to a variable.
name = input("Enter your name: ")
print("Hello", name)
Enter your name: Alice
Hello Alice
The value entered by the user is assigned to the variable
name.
Variables make mathematical calculations easier to understand and reuse.
length = 10
width = 5
area = length * width
print("Area =", area)
Area = 50
Using meaningful variables such as length,
width and area makes the purpose of the
calculation clear.
Python variables are not limited to individual numbers and strings. They can also refer to collections such as lists, tuples, sets and dictionaries.
fruits = ["apple", "banana", "cherry"]
print(fruits)
['apple', 'banana', 'cherry']
student = {
"name": "Alice",
"age": 20,
"score": 85
}
print(student)
{'name': 'Alice', 'age': 20, 'score': 85}
This makes variables essential for storing both simple values and complex data structures.
Good variable names make Python programs easier to understand. A variable should ideally describe the information it represents.
For example, this is less descriptive:
x = 450
A clearer alternative is:
total_marks = 450
The second example communicates the purpose of the value without requiring an additional explanation.
Python does not have a special keyword that makes a variable a true constant. However, Python programmers use naming conventions to indicate that a value should not be changed.
Constants are normally written using uppercase letters.
PI = 3.14159
MAX_SCORE = 100
print(PI)
print(MAX_SCORE)
3.14159
100
The uppercase names communicate to other programmers that these values are intended to remain constant. Python does not prevent the values from being reassigned.
Variable scope describes where a variable can be accessed in a Python program. Variables created inside functions and variables created outside functions can have different scopes.
A variable created inside a function is generally a local variable.
def greet():
message = "Hello Python"
print(message)
greet()
Hello Python
The variable message is created inside the function and is
local to that function.
A variable created outside a function is generally available at the module or global scope, while a variable created inside a function is local to that function unless other rules apply.
message = "Hello"
def greet():
print(message)
greet()
Hello
The function can access the variable message defined
outside the function.
Variable scope becomes increasingly important as Python programs become larger and functions are used to organize code.
Python provides the del statement to remove a name binding.
age = 25
print(age)
del age
After del age, the name age can no longer be
used to access the previously assigned object through that name.
Python provides the built-in id() function, which returns
an identity value for an object during its lifetime.
x = 10
print(id(x))
The exact number returned by id() can vary between
program executions and Python implementations. Beginners normally do
not need to use id() when working with ordinary variables,
but it can be useful when learning about Python objects and references.
A useful way to understand Python variables is to think of them as names referring to objects, rather than boxes that physically contain values.
For example:
x = 10
y = x
print(x)
print(y)
10
10
Both names can refer to the same integer object. This model becomes particularly important when working with mutable objects such as lists and dictionaries.
Beginners often encounter errors because of incorrect variable names, missing assignments or confusion about data types.
= with the comparison
operator ==.
The following example combines variables, user input, type conversion, calculations and formatted output.
name = input("Enter your name: ")
marks1 = float(input("Enter first mark: "))
marks2 = float(input("Enter second mark: "))
average = (marks1 + marks2) / 2
print()
print(f"Student: {name}")
print(f"Average mark: {average}")
Enter your name: Alice
Enter first mark: 80
Enter second mark: 90
Student: Alice
Average mark: 85.0
This example demonstrates why variables are so important. The program uses variables to hold user input, perform calculations and display the final result.
Following good variable naming and assignment practices makes Python code easier to read, debug and maintain.
student_name and
total_price.
x and
y when a more descriptive name would improve readability.
A Python variable is a name that refers to an object. Variables allow programs to work with values such as numbers, strings, lists and dictionaries.
A variable is created by assigning a value to a name using the
assignment operator =.
name = "Alice"
age = 25
No. Python does not normally require you to declare the data type when creating a variable. Python determines the type of the object assigned to the variable.
Yes. Python variables can refer to objects of different types at different times because Python is dynamically typed.
value = 10
value = "Python"
A Python variable name must start with a letter or underscore and can contain letters, numbers and underscores. It cannot contain spaces or hyphens, cannot start with a number and cannot be a Python keyword. Python variable names are also case-sensitive.
The = operator assigns a value to a variable, while
== compares two values to determine whether they are equal.
age = 20
age == 20
A local variable is a variable created within a function and normally available only within that function's local scope.
A global variable is a name defined at the module level. Depending on the scope rules, functions can read global names, while modifying a global name from inside a function requires additional consideration.
The commonly recommended style for ordinary Python variables is
snake_case, such as student_name,
total_price and average_score.
Python variables are names that refer to objects and allow programs to work with information throughout their execution. Variables can refer to numbers, strings, Boolean values, lists, dictionaries and many other Python objects.
Python uses dynamic typing, so you normally do not need to declare a
variable's data type before assigning a value. The type()
function can be used to inspect the type of an object.
Python variables can be reassigned, updated and used in calculations, conditions, loops, functions and data structures. Good variable names should be descriptive, follow Python's naming rules and normally use the snake_case convention.
Understanding variables is essential before moving on to more advanced Python topics such as data types, operators, conditional statements, loops, functions, lists, dictionaries and object-oriented programming.
Continue learning Python with these related beginner tutorials:
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net