Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 5

Variables, Names and Assignment

Store values with meaningful names, understand assignment, and follow conventions that keep programs readable.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026


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 Tag Analogy: Think of objects in Python as physical items sitting in a warehouse, and variables as sticky price tags attached to those items. Assigning a variable does not move the item; it simply sticks a name tag onto it.

The Memory Reference Model

When you write x = 100, Python executes three sequential internal steps:

  1. Creates an integer object in memory representing the value 100.
  2. Creates the identifier name x in the local namespace.
  3. Binds (links) the identifier x to reference the memory address of object 100.
+---------------+             +-----------------------+
| 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.

DYNAMIC_TYPING.PY
# 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))
OUTPUT
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, and TOTAL_AMOUNT are 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)
Python Reserved Keyword List:
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.

MULTIPLE_ASSIGNMENT.PY
# Assigning different values to multiple variables simultaneously
width, height, depth = 10, 20, 5

print("Width:", width)
print("Height:", height)
print("Depth:", depth)
OUTPUT
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:

SWAP_VARIABLES.PY
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)
OUTPUT
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()`

MEMORY_INSPECTION.PY
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))
OUTPUT
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

  1. Every object tracks how many variables or data structures reference it (its Reference Count).
  2. When a variable is re-bound or deleted using the del statement, the object's reference count drops by 1.
  3. 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

Q1: What is the fundamental difference between how variables store data in C/Java vs Python?
Answer: In C or Java, a variable is a typed memory container holding raw data directly. In Python, a variable is an untyped reference tag (pointer) pointing to an object stored in heap memory. The object holds the data type and value, not the variable name.
Q2: How does Python perform variable swapping without using a temporary third variable?
Answer: Python uses tuple packing and unpacking. In the expression 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.
Q3: What is the difference between the `==` operator and the `is` operator?
Answer: The == 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)).
Q4: What happens to an object in memory when all variables pointing to it are deleted or reassigned?
Answer: Its reference count drops to zero. Python's automatic Garbage Collector detects this unreferenced object and reclaims its allocated memory.
Q5: What is Integer Interning (Small Integer Caching) in CPython?
Answer: CPython pre-allocates and caches integer objects in the range of -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:

  1. total_price_2026
  2. #user_name
  3. import
  4. _private_key
  5. account-balance

Task 2: Swapping and Re-binding Lab

Create a script named swap_lab.py inside your lesson_05 directory:

  • Assign x = 50 and y = 100.
  • Print their memory addresses using id(x) and id(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

Next Up: Lesson 6 — Built-in Data Types and Type Conversion

Now that you understand how variables reference objects in memory, we will examine the built-in data types that Python provides.

In the next lesson, we will cover:

  • Numeric Types: Integers (int), Floats (float), and Complex Numbers (complex).
  • Text Sequence Type: Strings (str) and String Immutability.
  • Boolean Data Type (bool) and Truth Value Testing.
  • Implicit Type Conversion vs Explicit Type Casting using int(), float(), str(), and bool().
  • Handling type errors during input processing.

```

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat