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
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
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
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
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
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
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
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
| Name | Valid? | Reason |
|---|---|---|
| student_name | Yes | Letters and an underscore are allowed. |
| score2 | Yes | A digit can appear after the first character. |
| _count | Yes | An identifier may begin with an underscore. |
| total_price | Yes | A readable name using snake_case. |
| 2score | No | An identifier cannot begin with a digit. |
| first-name | No | A hyphen is an operator, not part of an identifier. |
| student name | No | An identifier cannot contain a space. |
| class | No | class 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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a variable in Python?
Q2:Is Python statically typed or dynamically typed?
Q3:What is the difference between = and ==?
Q4:What are the rules for naming variables in Python?
Q5:What is snake_case?
Q6:What is the difference between reassignment and mutation?
Q7:Why does changing a list through one name affect another name?
Q8:How can you swap two variables in Python?
Q9:What is chained assignment?
Q10:What causes a NameError?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: