๐ฆ Python Fundamentals
Module 2 ยท Topic 1
Variables & Memory Model
Variables in Python are references (labels) pointing to objects in memory โ understand this model to avoid subtle bugs.
Theory
Variables in Python โ The Reference Model:
Unlike C/C++ where a variable IS a memory box, in Python a variable is a label (reference) that points to an object in memory.
x = 42 # Creates an int object 42 in memory, x points to it
y = x # y now points to the SAME object 42
x = 100 # x now points to a new object 100, y still points to 42
Variable Naming Rules:
- Must start with a letter (a-z, A-Z) or underscore (_)
- Can contain letters, digits (0-9), and underscores
- Cannot start with a digit
- Cannot be a Python keyword (if, for, class, etc.)
- Case-sensitive:
age,Age, andAGEare three different variables
Python Naming Conventions (PEP 8):
snake_caseโ variables, functions, methods:user_name,calculate_total()PascalCaseโ classes:StudentProfile,BankAccountUPPER_SNAKE_CASEโ constants:MAX_RETRIES,API_KEY_single_leading_underscoreโ "private" (convention):_internal_value__double_leading_underscoreโ name mangling:__private_attr
The id() Function:
Every object in Python has a unique identity (memory address). Use id() to see it.
Python Keyword List (35 keywords in Python 3.12):
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
Syntax
# Variable assignment
variable_name = value
# Multiple assignment
a, b, c = 1, 2, 3
# Same value to multiple variables
x = y = z = 0
# Swap variables
a, b = b, a
# Check identity
id(variable)