1. What is a Variable in Python?
In traditional compiled languages like C, C++, or Java, a variable is viewed as a "box" or named memory slot of a fixed type and size where a literal value is directly stored. Changing the value overwrites the contents inside that specific memory address.
Python works differently: In Python, everything (integers, floats, strings, lists, functions) is an object residing in heap memory. A variable in Python is not a storage box—it is simply a name, reference, or pointer tag attached to an object in memory.
The Memory Reference Model
When you write x = 100, Python executes three sequential internal steps:
- Creates an integer object in memory representing the value
100. - Creates the identifier name
xin the local namespace. - Binds (links) the identifier
xto reference the memory address of object100.
+---------------+ +-----------------------+
| Variable Name | ----------> | Memory Object: 100 |
| (x) | (Points To)| Type: int |
+---------------+ | Ref Count: 1 |
+-----------------------+
2. Dynamic Typing and Object Rebinding
Python is a dynamically typed language. This means variables do not have fixed data types—only the objects they point to have types. You never explicitly declare a data type when creating a variable.
Because variables are merely references, a single variable name can point to an integer at one moment, a string at the next, and a list later in execution. This process is called re-binding or re-assignment.
# Variable points to an integer
data_payload = 404
print("Value:", data_payload, "| Type:", type(data_payload))
# Same variable re-bound to a string
data_payload = "HTTP 404 Not Found"
print("Value:", data_payload, "| Type:", type(data_payload))
# Same variable re-bound to a floating-point number
data_payload = 404.00
print("Value:", data_payload, "| Type:", type(data_payload))
Value: 404 | Type:Value: HTTP 404 Not Found | Type: Value: 404.0 | Type:
3. Variable Naming Rules and Identifier Guidelines
In Python, variable names are formal identifiers. To ensure your code compiles without error and adheres to professional engineering standards, follow these strict rules and PEP 8 guidelines:
A. Syntax Rules (Enforced by Python Interpreter)
- Allowed Characters: Variable names can contain letters (
A-Z,a-z), digits (0-9), and underscores (_). - First Character Rule: A variable name must start with a letter or an underscore (
_). It cannot start with a number. - Case Sensitivity: Identifiers are strictly case-sensitive.
total_amount,Total_Amount, andTOTAL_AMOUNTare three distinct variables. - No Reserved Keywords: Variable names cannot match any of Python's 35 reserved keywords (such as
class,def,if,import,return,for, etc.). - No Special Characters: Symbols like
@,$,%,-,!, or spaces are illegal inside identifiers.
B. Legal vs Illegal Variable Examples
| Identifier Name | Status | Reason / Standard Violation |
|---|---|---|
user_age |
Legal | Valid snake_case format. Starts with a letter. |
_session_id |
Legal | Starts with an underscore (commonly used for internal/private variables). |
2nd_user |
Illegal | Starts with a digit (triggers SyntaxError). |
user-name |
Illegal | Contains a hyphen (interpreted as subtraction operator user - name). |
class |
Illegal | Matches a reserved Python keyword (triggers SyntaxError). |
total$ |
Illegal | Contains illegal special character $. |
C. PEP 8 Naming Conventions
- Variables and Functions: Use snake_case (lowercase words separated by underscores). Examples:
item_count,calculate_total_price. - Constants: Use SCREAMING_SNAKE_CASE (all uppercase letters separated by underscores) for values meant to stay constant. Examples:
MAX_CONNECTIONS = 100,PI = 3.14159. - Classes: Use PascalCase (capitalize the first letter of each word). Example:
UserProfileManager.
4. Reserved Keywords in Python
Python retains a small set of words for its own syntax and structure. You cannot use these keywords as variable names. You can inspect all reserved keywords at any time directly from the interpreter:
import keyword print(keyword.kwlist)
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
5. Assignment Operators and Assignment Techniques
The equal sign (=) is the basic assignment operator in Python. It assigns the object on the right-hand side (RHS) to the variable name on the left-hand side (LHS).
1. Simple Assignment
# Syntax: variable_name = expression price = 49.99 product_title = "Wireless Headphones" is_available = True
2. Multiple Variable Assignment (Tuple Unpacking)
Python allows you to assign multiple variables in a single line. The number of variables on the left must match the number of expressions on the right.
# Assigning different values to multiple variables simultaneously
width, height, depth = 10, 20, 5
print("Width:", width)
print("Height:", height)
print("Depth:", depth)
Width: 10 Height: 20 Depth: 5
3. Swapping Variable Values Without a Temporary Variable
In traditional languages like C, swapping two variable values requires a temporary holding variable (temp). Python allows clean variable swapping in a single line using tuple unpacking:
a = "First Value"
b = "Second Value"
print("Before Swap -> a:", a, "| b:", b)
# Pythonic variable swap
a, b = b, a
print("After Swap -> a:", a, "| b:", b)
Before Swap -> a: First Value | b: Second Value After Swap -> a: Second Value | b: First Value
4. Chained Assignment
You can assign a single value to multiple variables simultaneously using chained assignment:
# All three variables point to the exact same integer object in memory x = y = z = 0 print(x, y, z) # Output: 0 0 0
5. Augmented Assignment Operators
Augmented assignment operators combine a standard binary arithmetic operation with an assignment operation into a concise expression:
| Augmented Operator | Equivalent Expanded Expression | Description |
|---|---|---|
x += 5 |
x = x + 5 |
Add and assign |
x -= 3 |
x = x - 3 |
Subtract and assign |
x *= 2 |
x = x * 2 |
Multiply and assign |
x /= 4 |
x = x / 4 |
Divide and assign (float output) |
x //= 2 |
x = x // 2 |
Floor divide and assign (integer output) |
x %= 10 |
x = x % 10 |
Modulus (remainder) and assign |
x **= 3 |
x = x ** 3 |
Exponentiate (power) and assign |
6. Object Identity, Memory Management, and the `id()` Function
To prove that variables are references to objects in memory, Python provides the built-in id() function. The id() function returns an object's unique integer memory address (or pointer address in CPython implementation).
Memory Inspection with `id()`
num_a = 500
num_b = num_a # Copying reference, not object
print("num_a value:", num_a, "| Memory Address:", id(num_a))
print("num_b value:", num_b, "| Memory Address:", id(num_b))
# Re-binding num_a to a new object
num_a = 600
print("--- After re-binding num_a ---")
print("num_a value:", num_a, "| Memory Address:", id(num_a))
print("num_b value:", num_b, "| Memory Address:", id(num_b))
num_a value: 500 | Memory Address: 140239482910224 num_b value: 500 | Memory Address: 140239482910224 --- After re-binding num_a --- num_a value: 600 | Memory Address: 140239482911856 num_b value: 500 | Memory Address: 140239482910224
Understanding Small Integer Caching (Integer Interning)
Optimization in Python: For performance reasons, CPython automatically caches (pre-allocates) integer objects in the range -5 through 256 when the interpreter starts up.
# Small integers share identical memory addresses a = 100 b = 100 print(a is b) # Output: True (Points to cached object 100) # Large integers create distinct objects in memory x = 1000 y = 1000 print(x is y) # Output: False (Two distinct objects in memory)
7. Garbage Collection and Reference Counting
Because Python manages memory automatically, developers do not need to manually allocate or deallocate memory (like malloc() or free() in C).
How Reference Counting Works
- Every object tracks how many variables or data structures reference it (its Reference Count).
- When a variable is re-bound or deleted using the
delstatement, the object's reference count drops by1. - When an object's reference count drops to
0, Python's automatic Garbage Collector frees that memory.
# Explicitly deleting a reference tag user_id = 9081 del user_id # Removes the variable name 'user_id' from namespace # Accessing user_id now raises a NameError!
8. Frequently Asked Interview Questions with Answers
a, b = b, a, Python first evaluates the right-hand side to create an implicit tuple (b, a) in memory, then unpacks the positional elements back into the left-hand side variable names a and b.
== operator compares equality of values (checks whether two objects hold equivalent contents). The is operator compares identity of memory addresses (checks whether two variables point to the exact same object in memory, equivalent to id(x) == id(y)).
-5 to 256 during startup. Any variable assigned a value within this range points to the existing cached object rather than creating a duplicate object in memory.
9. Homework & Practical Assignment
Task 1: Variable Identifier Audit
Analyze the variable names below. Classify each as Legal or Illegal. If illegal, state the rule broken:
total_price_2026#user_nameimport_private_keyaccount-balance
Task 2: Swapping and Re-binding Lab
Create a script named swap_lab.py inside your lesson_05 directory:
- Assign
x = 50andy = 100. - Print their memory addresses using
id(x)andid(y). - Swap their values using Pythonic single-line swapping (
x, y = y, x). - Verify that their memory addresses swapped accordingly.
Task 3: Dynamic Re-binding & Reference Trace
Write a script named reference_trace.py that defines a = 257, assigns b = a, then re-binds a = 300. Print both variables and their memory IDs using id() at each step. Explain in comments why b retains value 257.
10. File & Workspace Directory Structure
Standard Course Directory Structure:
Ensure all exercise files are stored inside their corresponding lesson directories:
python_mastery_course/
│
├── lesson_01/
│ └── homework_submission.md
│
├── lesson_02/
│ └── environment_setup_verification.txt
│
├── lesson_03/
│ └── hello.py
│
├── lesson_04/
│ └── conditional_block.py
│
└── lesson_05/
├── dynamic_typing.py
├── multiple_assignment.py
├── swap_variables.py
├── memory_inspection.py
├── swap_lab.py
└── reference_trace.py
11. What We Will Learn Next
```
OnlineCBT