Skip to content
PythonVariables and Basic Databeginner30 min read

Variables in Python

Understand variables, name binding, reassignment, naming rules, multiple assignment, and the difference between changing a name and changing an object.

In this lesson, you will learn

  • ✓Explain variables as names bound to objects.
  • ✓Create, read, and reassign variables using the assignment operator =.
  • ✓Distinguish assignment = from equality comparison ==.
  • ✓Identify valid identifiers and follow Python naming conventions.
  • ✓Explain case sensitivity, multiple assignment, and swapping values.
  • ✓Distinguish rebinding a name from mutating a mutable object.
  • ✓Recognize NameError and troubleshoot common assignment mistakes.

1. What Is a Variable?

A **variable** is commonly described as a name used to refer to a value. More precisely, in Python, a name is bound to an object. That object might represent an integer, a string, a list, or another kind of data.

Variables make programs easier to read and maintain. Instead of repeating a number throughout your code, you can give it a meaningful name and use that name wherever the value is needed.

Python uses the assignment operator **=** to bind a name to the result of an expression. The name appears on the left side, and the expression appears on the right side.

For example, `age = 21` binds the name `age` to the integer object representing 21. Later, `print(age)` looks up the object currently associated with `age` and displays its value.

The equals sign in an assignment is not the same as the equality operator `==`. Assignment establishes a binding; equality comparison checks whether two values compare equal.

Create and use a variable

Create and use a variable
python
age = 21
print(age)
Output
21

Python evaluates the integer literal 21. The name age is bound to the resulting integer object. The next statement looks up age. print() displays the value associated with age.

Note

In Python, a variable name refers to an object. The name can later be rebound to another object, including one of a different type.

2. Assignment and Reassignment

**Assignment** creates or updates a binding between a name and an object. **Reassignment** means assigning a name again so that it refers to a new object or value.

For example, after `score = 10`, reading score produces 10. If you then execute `score = 15`, the name score refers to the new integer value 15.

Python is dynamically typed. Objects have types, but an ordinary variable name does not have to remain associated with one type for its entire lifetime.

This means the same name can refer to an integer first and a string later. Although Python permits this, changing a variable’s meaning or type unexpectedly can make a program harder to understand.

The right-hand side of an assignment is evaluated before the resulting object is bound to the target name. This allows an existing variable to be used to calculate its next value.

Reassign a variable

Reassign a variable
python
score = 10
print(score)
score = 15
print(score)
Output
10 15

The first assignment binds score to 10. The first print() call displays 10. The next assignment rebinds score to 15. The final print() call looks up the updated binding and displays 15.

Note

The statement balance = balance + 25 is valid because the right side is evaluated using the existing binding before the new result is assigned.

3. Assignment (=) Versus Equality (==)

These two operators look similar, but they perform different operations.

- **`=` — assignment:** binds a name to the object produced by the expression on the right.

- **`==` — equality comparison:** compares two values and evaluates to a Boolean result, `True` or `False`.

For example, `number = 5` assigns a value. The expression `number == 5` checks whether the current value of number is equal to 5.

A comparison can be used in conditions and displayed using print(). Writing `number == 5` does not assign 5 to number, and writing `number = 5` is not an equality test.

Assign a value, then compare it

Assign a value, then compare it
python
number = 5
print(number == 5)
print(number == 8)
Output
True False

The first statement assigns 5 to number. The expression number == 5 evaluates to True. The expression number == 8 evaluates to False. Both comparison results are displayed by print().

Note

Remember: use one equals sign to assign, and two equals signs to compare for equality.

4. Rules for Valid Variable Names

A variable name is an **identifier**. Python checks identifiers against its language rules before executing a program.

For ordinary beginner code using English letters, digits, and underscores, remember these rules:

- A name may contain letters, digits, and underscores.

- A name cannot begin with a digit.

- A hyphen is not allowed inside an identifier because it is interpreted as an operator.

- Names are case-sensitive: `count`, `Count`, and `COUNT` are different names.

- Reserved keywords, such as `if`, `for`, and `class`, cannot be used as ordinary variable names.

- Spaces are not allowed inside a single identifier.

Python also supports many Unicode letters in identifiers, but beginner projects commonly use English letters and underscores for consistency and readability.

The rules determine whether a name is valid. Naming conventions, covered in the next section, help determine whether it is easy to understand.

Valid variable names

Valid variable names
python
student_name = "Asha"
score2 = 95
_count = 1
print(student_name)
print(score2)
print(_count)
Output
Asha 95 1

student_name uses letters and an underscore. score2 contains a digit after the first character. _count begins with an underscore. All three names are valid and can be used in assignments.

Note

An identifier being valid does not automatically make it a good name. Prefer names that clearly communicate the value’s purpose.
4. Rules for Valid Variable Names Reference
NameValid?Reason
student_nameYesLetters and an underscore are allowed.
score2YesA digit can appear after the first character.
_countYesAn identifier may begin with an underscore.
total_priceYesA readable name using snake_case.
2scoreNoAn identifier cannot begin with a digit.
first-nameNoA hyphen is an operator, not part of an identifier.
student nameNoAn identifier cannot contain a space.
classNoclass is a reserved keyword.

5. Naming Conventions and Readability

Python naming conventions are recommendations for making code consistent and understandable. They are not all syntax requirements.

For ordinary variables, the common convention is **snake_case**: use lowercase words separated by underscores. Examples include `student_name`, `total_price`, and `number_of_attempts`.

Choose names that describe the meaning of the value. A name such as total_price is easier to understand than a vague name such as x when calculating a shopping bill.

Avoid using names that hide or replace built-in functions and types. For example, assigning a value to `list` can hide the built-in list constructor within that scope and make later code confusing.

Python permits names such as `totalPrice`, but snake_case is the usual convention for ordinary variables. Follow the style already used by a project when contributing to existing code.

Use descriptive variable names

Use descriptive variable names
python
item_price = 120
quantity = 3
total_price = item_price * quantity
print(total_price)
Output
360

item_price describes the price of one item. quantity describes how many items are being purchased. total_price stores the result of multiplying price by quantity. The descriptive names make the calculation easier to understand without extra comments.

Note

A good variable name communicates intent. Consistent naming makes programs easier to review, debug, and extend.

6. Multiple Assignment and Unpacking

Python allows more than one name to be assigned in a single statement. Two useful forms are **multiple assignment** and **chained assignment**.

In an unpacking assignment such as `x, y = 4, 9`, Python evaluates the right-hand side and assigns the corresponding values to the targets. Here, x receives 4 and y receives 9.

In chained assignment such as `a = b = 10`, both names are bound to the same object produced by the right-hand expression. This is straightforward with an immutable integer, but remember that chained assignment with a mutable object such as a list gives both names a reference to the same list.

Unpacking is also useful for swapping values. The statement `left, right = right, left` evaluates the right-hand values before assigning the results to the left-hand targets. It swaps the two bindings without requiring a temporary variable.

For a simple unpacking assignment, the number of targets must match the number of unpacked values. If the counts do not match and no starred target is used, Python raises a ValueError.

Assign two values at once

Assign two values at once
python
x, y = 4, 9
print(x)
print(y)
Output
4 9

Python evaluates the two values on the right-hand side. The first value is assigned to x. The second value is assigned to y. The two print() calls display the resulting bindings.

Note

Multiple assignment is convenient, but use separate assignments when they make a complicated operation easier to understand.

7. Names, Objects, and Mutable Values

One of the most important Python concepts is the difference between a **name** and the **object** it refers to. Assignment binds a name to an object; ordinary assignment does not automatically copy that object.

Some objects are **mutable**, which means their contents can change after creation. Lists and dictionaries are common examples. Integers and strings are **immutable**, which means their values cannot be changed in place.

Consider `first = [1, 2]` followed by `second = first`. Both names refer to the same list object. If you execute `second.append(3)`, you mutate that shared list, so looking through either name shows the updated list.

Rebinding a name is different. If you subsequently execute `second = [7, 8]`, the name second refers to a new list. The name first still refers to the original list.

This distinction is important when you pass lists or dictionaries to functions, store them in data structures, or share them between different parts of a program.

Two names refer to the same list

Two names refer to the same list
python
first = [1, 2]
second = first
second.append(3)
print(first)
print(second)
Output
[1, 2, 3] [1, 2, 3]

first is bound to a list containing 1 and 2. second = first binds second to that same list; it does not make a copy. second.append(3) mutates the shared list. Both names therefore display the updated contents.

Note

Assignment does not copy a list. Use list.copy() or another appropriate copying technique when you need a separate outer list. Remember that a shallow copy does not duplicate nested objects.

8. Common Errors with Variables

**NameError:** Python cannot find a binding for the name being read in the current scope. A common cause is using a variable before assigning it.

**SyntaxError:** the code does not follow Python syntax. For example, `10 = score` is invalid because a literal number cannot be used as an assignment target.

**TypeError:** an operation does not support the supplied types. For example, adding a string directly to an integer with `+` raises TypeError.

**Unexpected shared changes:** two names may refer to the same mutable object. Mutating it through one name can change what is observed through the other.

When an error occurs, inspect the specific line and message. Determine whether the problem concerns an undefined name, invalid syntax, incompatible types, or shared object state before changing the code.

Fix a NameError

Fix a NameError
python
price = 50
print(price)
Output
50

The assignment creates a binding for price. The next statement reads an existing name. Because price has been assigned, the program can display its value. Reading a name with no binding in the current scope would ordinarily raise NameError.

Note

If a variable behaves unexpectedly, check its current value, type, scope, and whether another name refers to the same mutable object.

9. Apply Variables to a Small Program

Variables become especially useful when several values contribute to one result. Instead of embedding every number directly in a calculation, assign each piece of information a descriptive name.

The following example calculates the total cost of a small purchase. It demonstrates assignment, multiplication, reassignment, and printing a result.

Trace the program in order. Before each statement runs, ask which names already exist and which values they refer to. After the calculation, check which binding changes.

Calculate a shopping total

Calculate a shopping total
python
item_price = 40
quantity = 3
total_price = item_price * quantity
print(total_price)
total_price = total_price - 10
print(total_price)
Output
120 110

item_price is assigned 40 and quantity is assigned 3. Python calculates 40 * 3 and assigns 120 to total_price. The first print() displays 120. The next assignment reads the current total, subtracts 10, and rebinds total_price to 110. The final print() displays the updated total, 110.

Note

This example is a simple calculation, not a complete billing system. A real application would also need to define its currency, validate inputs, and handle discounts according to its requirements.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Using = when you want to compare two values.

Why it happens: Assignment and equality use similar symbols, but = binds a value to a name while == evaluates whether two values compare equal.

Incorrect Approach
script.py
python
Using = when you want to compare two values.
Correct Solution
script.py
python
Use = to assign a value and == to test equality. For example, score = 10 assigns 10, while score == 10 evaluates to True or False.

Key takeaway: Use = to assign a value and == to test equality. For example, score = 10 assigns 10, while score == 10 evaluates to True or False.

#2 Thinking that a variable has a permanent data type.

Why it happens: Learners may carry over static-typing rules from other languages; Python names can be rebound even though each referenced object has its own type.

Incorrect Approach
script.py
python
Thinking that a variable has a permanent data type.
Correct Solution
script.py
python
Python is dynamically typed. A name can be rebound to an object of another type, although keeping a variable’s meaning consistent usually improves readability.

Key takeaway: Python is dynamically typed. A name can be rebound to an object of another type, although keeping a variable’s meaning consistent usually improves readability.

#3 Assuming that second = first copies a list.

Why it happens: Assignment creates another reference to the same list, not a new list object, so mutations can be visible through both names.

Incorrect Approach
script.py
python
Assuming that second = first copies a list.
Correct Solution
script.py
python
The assignment binds both names to the same list object. Use first.copy() when a shallow copy is suitable.

Key takeaway: The assignment binds both names to the same list object. Use first.copy() when a shallow copy is suitable.

#4 Using a number as the first character of a variable name.

Why it happens: Python identifiers cannot begin with a digit because the parser would interpret the leading characters as a numeric literal.

Incorrect Approach
script.py
python
Using a number as the first character of a variable name.
Correct Solution
script.py
python
Start an ordinary identifier with a letter or underscore. For example, use score2 rather than 2score.

Key takeaway: Start an ordinary identifier with a letter or underscore. For example, use score2 rather than 2score.

#5 Using a Python keyword as a variable name.

Why it happens: Keywords such as class and if are reserved by the language grammar and cannot be used as ordinary variable identifiers.

Incorrect Approach
script.py
python
Using a Python keyword as a variable name.
Correct Solution
script.py
python
Choose another identifier. Use class_name instead of class, or if_condition instead of if.

Key takeaway: Choose another identifier. Use class_name instead of class, or if_condition instead of if.

#6 Assuming that capitalization does not matter.

Why it happens: Python distinguishes uppercase and lowercase letters in identifiers, so capitalization differences create different names.

Incorrect Approach
script.py
python
Assuming that capitalization does not matter.
Correct Solution
script.py
python
Python identifiers are case-sensitive. Treat name, Name, and NAME as different names.

Key takeaway: Python identifiers are case-sensitive. Treat name, Name, and NAME as different names.

#7 Expecting reassignment to update every name that once referred to the same object.

Why it happens: Reassignment changes the binding of one name only; it does not update other names, although mutating an object shared by several names is visible through each reference.

Incorrect Approach
script.py
python
Expecting reassignment to update every name that once referred to the same object.
Correct Solution
script.py
python
Rebinding one name changes only that name’s binding. Mutating a shared mutable object, however, can be observed through all names referring to it.

Key takeaway: Rebinding one name changes only that name’s binding. Mutating a shared mutable object, however, can be observed through all names referring to it.

#8 Using a built-in name such as list for an ordinary variable.

Why it happens: Reusing a built-in name shadows the built-in within that scope, which can make later calls behave unexpectedly or fail.

Incorrect Approach
script.py
python
Using a built-in name such as list for an ordinary variable.
Correct Solution
script.py
python
Choose a descriptive alternative such as numbers or student_list so the built-in list constructor remains accessible.

Key takeaway: Choose a descriptive alternative such as numbers or student_list so the built-in list constructor remains accessible.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a variable in Python?
Answer:
A variable is a name used to refer to an object. Assignment binds the name to the object produced by the right-hand expression. A name can later be rebound to another object.
Q2:Is Python statically typed or dynamically typed?
Answer:
Python is dynamically typed. Objects have types, but an ordinary name is not permanently declared to one type and can be rebound to objects of different types.
Q3:What is the difference between = and ==?
Answer:
= is the assignment operator, used to bind a name to an object. == is an equality comparison operator that evaluates to a Boolean result.
Q4:What are the rules for naming variables in Python?
Answer:
For ordinary identifiers, names can contain letters, underscores, and digits after the first character. They cannot start with a digit or use reserved keywords. Python identifiers are case-sensitive. Python also supports many Unicode letters, although English letters and underscores are common in beginner code.
Q5:What is snake_case?
Answer:
snake_case is a naming convention in which words are lowercase and separated by underscores, such as total_price or student_name. It is the usual convention for ordinary Python variables, but it is not a syntax requirement.
Q6:What is the difference between reassignment and mutation?
Answer:
Reassignment binds a name to another object. Mutation changes the contents or state of an existing mutable object, such as a list. Other names referring to that same object can observe the mutation.
Q7:Why does changing a list through one name affect another name?
Answer:
If second = first assigns a list reference to another name, both names refer to the same list object. Mutating that list through second also changes the object observed through first.
Q8:How can you swap two variables in Python?
Answer:
Use multiple assignment: a, b = b, a. Python evaluates the right-hand values before unpacking them into the left-hand targets, so a temporary variable is unnecessary for this basic swap.
Q9:What is chained assignment?
Answer:
Chained assignment binds multiple targets to the same object produced by a right-hand expression, as in a = b = 10. If the expression produces a mutable object, both names refer to that same object unless a later operation rebinds one of them.
Q10:What causes a NameError?
Answer:
A NameError occurs when Python cannot resolve a name being accessed in the current scope. Common causes include misspelling a variable, reading it before it has been bound, or referring to a name that is unavailable in the current scope.

Key takeaways

  • A Python variable is a name bound to an object.
  • The assignment operator = binds a name; the equality operator == compares values.
  • Python is dynamically typed, so a name can be rebound to an object of another type.
  • Python identifiers are case-sensitive and must follow the language naming rules.
  • snake_case is the usual convention for ordinary Python variable names.
  • Multiple assignment can unpack values and swap two names.
  • Assignment does not automatically copy a list or dictionary.
  • Mutating a shared mutable object can be observed through every name referring to that object.
  • Rebinding a name does not automatically rebind other names that previously referred to the same object.
  • Read error messages carefully to distinguish NameError, SyntaxError, and TypeError.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: