Python Variables: Dynamic Typing, Memory References & Scope

In Python, variables are symbolic names bound to objects in memory.

Dynamic Typing & Object References: Unlike statically typed languages where variables represent fixed memory locations, Python variables act as pointers to objects. Inspect an object's type with type(), verify its memory address using id(), or convert types with int(), float(), and str(). For naming constraints, consult reserved keywords and learn namespace isolation in variable scope.

Python variables
Infographic: Python's "Name Tag" Memory Model vs. Fixed Box Model
C / C++ Model Python Reference Model
Fixed Container: Variable is a fixed RAM slot of a single type.
int x = 5; → [Memory Slot 0x100: Value 5]
Name Tag / Pointer: Variable is a pointer to an object on the heap.
x = 5 → Variable x points to PyObject_Int(value=5)
Reassignment overwrites memory bytes directly. Reassignment moves the pointer to a new object.

Video Tutorial: Rules for Naming Variables in Python

1. Python Variable Naming Rules & Identifiers 🔝

Every variable name in Python is an identifier. Identifiers must follow standard syntactic rules:

  • Allowed Characters: Alphanumeric characters (letters a-z, A-Z, digits 0-9) and the underscore (_).
  • Starting Character: Must begin with a letter or an underscore. It cannot start with a digit (e.g. 4t = 56 triggers a SyntaxError).
  • No Special Symbols: Symbols like $, @, #, %, and hyphens (-) are invalid.
  • Case-Sensitivity: student_age, Student_Age, and STUDENT_AGE are three distinct variables.
  • Reserved Keywords: You cannot use Python keywords such as for, class, def, or global as variable names (see reserved keywords).
  • Identifier Validation: You can programmatically check if a string is a valid identifier using the string method str.isidentifier().

2. Variable Declaration & Multi-Variable Assignment 🔝

Variables are initialized automatically the moment they are assigned a value using the assignment operator (=):

# 1. Variable Declaration and Multiple Assignment
a = 45
my_name = "Raju"
_mark = 65
address = "World"

print("Values:", address, my_name, _mark, a)

# Multiple assignment in a single statement
width, height = 710, 710
x1, y1, x2, y2 = 5, 5, width - 5, height - 5
print(f"Dimensions: {width}x{height}, Box: ({x1}, {y1}) to ({x2}, {y2})")

Terminal Output:

Values: World Raju 65 45
Dimensions: 710x710, Box: (5, 5) to (705, 705)
Python variables declaration and naming conventions with rules with sample code using Google Colab:

3. Dynamic Typing & Type Reassignment 🔝

Python is dynamically typed. A variable does not have a permanently locked type; rather, it takes on the type of whatever object it currently references:

# 2. Dynamic Typing and Type Reassignment
val = "plus2net"
print("Initial type:", type(val), "-> Value:", val)

# Reassigning the same variable name to an integer
val = 420
print("Updated type:", type(val), "-> Value:", val)

Terminal Output:

Initial type: <class 'str'> -> Value: plus2net
Updated type: <class 'int'> -> Value: 420
Python Variables Explained in Simple Words | Colab Demo:

4. Memory Addresses & Identity Verification (id() & is) 🔝

When you assign one variable to another (y = x), you create an alias pointing to the exact same object in memory. You can inspect the unique memory address using id():

# 3. Python Object Pointer Model: Name Tags vs. Memory Objects
x = [1, 2, 3]
y = x          # y references the exact same object in heap memory
print("id(x) == id(y):", id(x) == id(y))
print("x is y:        ", x is y)

y.append(4)
print("x after y.append():", x)

Terminal Output:

id(x) == id(y): True
x is y:         True
x after y.append(): [1, 2, 3, 4]
Understanding Python Variables Part 2:

5. Operations Between Different Types & Explicit Conversions 🔝

Python prevents implicit operations between incompatible types (such as adding an integer to a string). You must convert types explicitly using constructor functions:

# 4. Explicit Type Conversions Between Data Types
a = "45"  # String representation
b = 42    # Integer literal

# Adding a string and integer directly raises TypeError:
# print(a + b)  # TypeError: can only concatenate str to str

print("Concatenation as text: ", a + str(b))
print("Mathematical addition: ", int(a) + b)

Terminal Output:

Concatenation as text:  4542
Mathematical addition:  87

6. Packing & Sequence Unpacking 🔝

Python allows unpacking iterables (such as lists or tuples) directly into variables, as well as swapping variables without temporary variables:

# 5. Variable Packing and Extended Unpacking (* operator)
# Swapping variables without temporary storage
x, y = 5, 10
x, y = y, x
print(f"Swapped: x={x}, y={y}")

# Extended sequence unpacking
user_data = "plus2net"
first, second, *rest = user_data
print("First: ", first)
print("Second:", second)
print("Rest:  ", rest)

Terminal Output:

Swapped: x=10, y=5
First:  p
Second: l
Rest:   ['u', 's', '2', 'n', 'e', 't']

7. Variable Scope: Local, Global & Nonlocal 🔝

Variables declared inside a function have local scope and are destroyed when the function exits. Variables declared at the script level have global scope:

  • Local Scope: Accessible only inside the enclosing function block.
  • Global Scope: Accessible throughout the entire module. To modify a global variable inside a function, declare it with global var_name.
  • Nonlocal Scope: Used in nested functions to modify variables in the outer enclosing scope without making them global. Learn more in global, local & nonlocal variables.

8. Deleting Variables (del) & Exception Handling 🔝

Use the del statement to remove a variable name from the namespace. Subsequent access raises a NameError, which can be handled using try...except error handling:

# 6. Deleting Variables with del & NameError Handling
counter = 100
print("Counter exists:", counter)

del counter
try:
    print(counter)
except NameError as err:
    print("Caught expected exception:", err)

Terminal Output:

Counter exists: 100
Caught expected exception: name 'counter' is not defined

9. Constants in Python 🔝

Python has no keyword for immutable constants. Instead, PEP 8 defines a naming convention using all-uppercase letters with underscores to indicate values that should remain unchanged:

# 7. Constant Conventions in Python (UPPER_CASE naming)
# Python does not enforce immutable constants at the syntax level;
# by PEP 8 convention, constants are written in uppercase.
PI = 3.14159
MAX_CONNECTIONS = 500
BASE_URL = "https://www.plus2net.com"

print("API Endpoint:", f"{BASE_URL}/api/v1")
print("Max limit:   ", MAX_CONNECTIONS)

Terminal Output:

API Endpoint: https://www.plus2net.com/api/v1
Max limit:    500

10. Interactive Practice & Companion Jupyter Notebook 🔝

Practice variable assignment, object pointer inspections, type conversions, and scope rules in our interactive companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells, verify memory IDs with id(), practice sequence unpacking, and run self-validating assertions.

View on GitHub Run in Google Colab

Self-Verifying Assertion Suite

Run these unit checks directly in Python or your local environment to verify variable mechanics:

# 8. Self-verifying unit test suite for variable operations
# Test 1: Multiple assignment
a, b = 10, 20
assert a == 10 and b == 20

# Test 2: In-place value swap
a, b = b, a
assert a == 20 and b == 10

# Test 3: Type conversion
s = "100"
assert int(s) == 100
assert str(50) == "50"

# Test 4: Extended unpacking
h, *tail = [1, 2, 3, 4]
assert h == 1 and tail == [2, 3, 4]

# Test 5: Deletion raising NameError
tmp = 999
del tmp
try:
    _ = tmp
    assert False, "NameError not raised"
except NameError:
    pass

print("All variable unit assertions successfully verified!")

Terminal Output:

All variable unit assertions successfully verified!

11. Frequently Asked Questions (FAQ) 🔝

Do I need to declare variable types in Python?

No. Python is dynamically typed; variables are created automatically upon assignment and infer their data type from the assigned value.

Can a variable start with a number?

No. Variable names must start with an alphabetic letter (a-z, A-Z) or an underscore (_). Starting with a digit causes a SyntaxError.

How do I swap two variables in Python?

Use tuple unpacking: x, y = y, x. Python evaluates the right-hand side first, swapping values without a temporary variable.

Are constants truly constant in Python?

Python does not have built-in constants. The convention is to use uppercase variable names (e.g., MAX_LIMIT = 100) to signal they should not be modified.

Further Reading & Related Tutorials 🔝

  • Python Variables #python #variables (11-Feb-2024) Python Variables Tutorial



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer