๐Ÿ“ฆ 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:

  1. Must start with a letter (a-z, A-Z) or underscore (_)
  2. Can contain letters, digits (0-9), and underscores
  3. Cannot start with a digit
  4. Cannot be a Python keyword (if, for, class, etc.)
  5. Case-sensitive: age, Age, and AGE are three different variables

Python Naming Conventions (PEP 8):

  • snake_case โ€” variables, functions, methods: user_name, calculate_total()
  • PascalCase โ€” classes: StudentProfile, BankAccount
  • UPPER_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)