Python Tutoring Online
 Home            

Python Variables – How to Create, Use and Change Variables

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.

What Is a Variable in Python?

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:

Python
age = 25

print(age)

Output


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.

How to Create a Variable in Python

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:

Python
name = "Alice"
age = 25
city = "London"

Three variables have been created:

Python Variable Assignment

The process of giving a value to a variable is called variable assignment. Python uses the = operator for assignment.

Python
score = 85

print(score)

Output


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.

Using Variables in Python Programs

Once a variable has been created, you can use its name whenever you need to access the value.

Python
price = 50
quantity = 3

total = price * quantity

print(total)

Output


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.

Variables Can Store Different Data Types

Python variables can refer to objects of many different data types. Common examples include integers, floating-point numbers, strings, Boolean values, lists and dictionaries.

Python
name = "Alice"
age = 25
height = 5.6
is_student = True

print(name)
print(age)
print(height)
print(is_student)

Output


Alice
25
5.6
True

In this example:

Checking the Type of a Python Variable

Python provides the built-in type() function to determine the type of object referred to by a variable.

Python
age = 25

print(type(age))

Output


<class 'int'>

You can check several variables in the same program.

Python
name = "Alice"
age = 25
height = 5.6
is_student = True

print(type(name))
print(type(age))
print(type(height))
print(type(is_student))

Output


<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Python Variables Are Dynamically Typed

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.

Python
age = 25

print(type(age))

You can later assign a string to the same variable name:

Python
value = 25

print(type(value))

value = "Python"

print(type(value))

Output


<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.

Changing the Value of a Variable

A variable can be assigned a new value during program execution.

Python
age = 25

print(age)

age = 30

print(age)

Output


25
30

The name age first refers to the value 25. After the second assignment, it refers to 30.

Updating a Variable Using Its Existing Value

Variables are often updated using their current value. This is useful for counters, totals and calculations.

Python
score = 50

score = score + 10

print(score)

Output


60

Python first evaluates score + 10 and then assigns the result back to score.

Using Assignment Operators with Variables

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

Example: Using +=

Python
score = 50

score += 10

print(score)

Output


60

The statement score += 10 adds 10 to the existing value of score.

Rules for Naming Python Variables

Python variable names must follow certain rules. Following these rules prevents syntax errors and makes programs easier to understand.

Valid Python Variable Names

The following are examples of valid Python variable names:

Python
name = "Alice"
_age = 25
student1 = "John"
student_name = "Mary"
total_marks = 95

These names follow Python's variable naming rules.

Invalid Python Variable Names

Some names cannot be used as Python variables because they violate the language's naming rules.

Python
1name = "Alice"
student-name = "John"
student name = "Mary"

These examples are invalid because:

A better approach is to use underscores to separate words.

Python
student_name = "Mary"

Python Variable Names Are Case-Sensitive

Python treats uppercase and lowercase letters as different. Therefore, name, Name and NAME can refer to different variables.

Python
name = "Alice"
Name = "Bob"
NAME = "Charlie"

print(name)
print(Name)
print(NAME)

Output


Alice
Bob
Charlie

For this reason, it is important to use consistent capitalization when writing Python programs.

Python Variable Naming Conventions

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.

Python
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 Keywords Cannot Be Variable Names

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:

Python
condition = 10

Assigning Multiple Variables in Python

Python allows multiple variables to be assigned values in a single statement.

Python
name, age, city = "Alice", 25, "London"

print(name)
print(age)
print(city)

Output


Alice
25
London

The values are assigned from left to right to the corresponding variable names.

Assigning the Same Value to Multiple Variables

Python also allows the same value to be assigned to several variables at once.

Python
x = y = z = 0

print(x)
print(y)
print(z)

Output


0
0
0

This can be useful when several variables need the same initial value.

Swapping Two Variables in Python

Python provides a convenient way to exchange the values of two variables without requiring a temporary variable.

Python
a = 10
b = 20

a, b = b, a

print(a)
print(b)

Output


20
10

This is a useful and commonly demonstrated feature of Python variable assignment.

Variables and User Input

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.

Python
name = input("Enter your name: ")

print("Hello", name)

Output Example


Enter your name: Alice
Hello Alice

The value entered by the user is assigned to the variable name.

Variables and Mathematical Calculations

Variables make mathematical calculations easier to understand and reuse.

Python
length = 10
width = 5

area = length * width

print("Area =", area)

Output


Area = 50

Using meaningful variables such as length, width and area makes the purpose of the calculation clear.

Variables Can Refer to Collections

Python variables are not limited to individual numbers and strings. They can also refer to collections such as lists, tuples, sets and dictionaries.

Example: Variable Containing a List

Python
fruits = ["apple", "banana", "cherry"]

print(fruits)

Output


['apple', 'banana', 'cherry']

Example: Variable Containing a Dictionary

Python
student = {
    "name": "Alice",
    "age": 20,
    "score": 85
}

print(student)

Output


{'name': 'Alice', 'age': 20, 'score': 85}

This makes variables essential for storing both simple values and complex data structures.

Variable Names and Descriptive Programming

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 Variables and Constants

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.

Python
PI = 3.14159
MAX_SCORE = 100

print(PI)
print(MAX_SCORE)

Output


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.

Python Variable Scope

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.

Python
def greet():
    message = "Hello Python"
    print(message)

greet()

Output


Hello Python

The variable message is created inside the function and is local to that function.

Local and Global Variables in Python

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.

Python
message = "Hello"

def greet():
    print(message)

greet()

Output


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.

Deleting a Python Variable

Python provides the del statement to remove a name binding.

Python
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.

Using the id() Function with Variables

Python provides the built-in id() function, which returns an identity value for an object during its lifetime.

Python
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.

Python Variables Are Names That Refer to Objects

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:

Python
x = 10
y = x

print(x)
print(y)

Output


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.

Common Python Variable Mistakes

Beginners often encounter errors because of incorrect variable names, missing assignments or confusion about data types.

Example of a Well-Structured Python Program Using Variables

The following example combines variables, user input, type conversion, calculations and formatted output.

Python
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}")

Output Example


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.

Best Practices for Python Variables

Following good variable naming and assignment practices makes Python code easier to read, debug and maintain.

Frequently Asked Questions About Python Variables

What is a variable in Python?

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.

How do you create a variable in Python?

A variable is created by assigning a value to a name using the assignment operator =.


name = "Alice"
age = 25

Do Python variables need a data type declaration?

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.

Can a Python variable change its data type?

Yes. Python variables can refer to objects of different types at different times because Python is dynamically typed.


value = 10
value = "Python"

What are the rules for naming variables in 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.

What is the difference between = and == in Python?

The = operator assigns a value to a variable, while == compares two values to determine whether they are equal.


age = 20

age == 20

What is a local variable in Python?

A local variable is a variable created within a function and normally available only within that function's local scope.

What is a global variable in Python?

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.

What naming style should Python variables use?

The commonly recommended style for ordinary Python variables is snake_case, such as student_name, total_price and average_score.

Summary of Python Variables

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.

Related Python Tutorials

Continue learning Python with these related beginner tutorials:

Need Help Learning Python?

Having difficulty understanding Python variables, data types, operators or other Python fundamentals? An experienced online Python tutor can help you learn Python through clear explanations, practical coding examples and guided practice.

One-to-one Python tutoring provides personalized help with Python fundamentals, programming assignments, projects and coding problems.

Get Python Tutoring Help




Stuck Learning Python?

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.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net