Definition
Labels that represent values stored in computer memory. They allow programmers to refer to data using descriptive names rather than memory addresses.
Why It Matters
In Python, failing to understand the “name tag” model leads to catastrophic “invisible” bugs where changing one variable unexpectedly alters another. Mastery of state management is what separates a coder from a systems engineer.
Core Concepts
- Mental Model Hierarchy:
- The “Box” Model (Beginner Abstraction): A variable is like a labeled box that holds one value. While intuitive, this is a “useful lie” that simplifies initial learning.
- The “Name Tag” Model (Underlying Reality): In Python, variables are better thought of as labels or name tags attached to objects in memory. This distinction is critical for understanding References (Python) and side effects in mutable types.
- Initialization Requirement: A variable cannot be used until it has been assigned a value (initialized). Attempting to use an undefined variable results in a
NameError. - Naming Conventions:
- Letters, numbers, underscores only; cannot start with a number.
- No spaces (use
snake_case). - Descriptive over brief (e.g.,
user_agevsu_a).
- Dynamic Reassignment: Assigning a new value simply moves the “name tag” to a new object. The old object, if no longer referenced, is eventually reclaimed by memory.
# Initial assignment (initialization)
message = "Hello Python!"
print(message)
# Dynamic reassignment to a different type
message = 42
print(message) # The label 'message' now points to an integer object