Variables & Memory
Beginner · 18 min read · ▶ live playground · ✦ checkpoint
Every program you'll ever write does one thing constantly: it remembers. A score, a username, a running total — programs hold onto values and give them names. Those names are variables, and getting an accurate mental picture of them now pays off for the rest of your Python life — because Python's variables don't work quite the way most beginners assume.
What a variable really is
Here's the assignment statement, the single most common line in all of Python:
score = 0
player = "Ada"Read = as "now refers to", not "equals": the name score now refers to the value 0. Python creates the value in memory, then attaches the name to it — like a sticky label on a box.
The order matters: the right side runs first. Python evaluates whatever's right of =, gets a value, then binds the name on the left to it. That's why this line — which looks like nonsense algebra — is perfectly ordinary Python:
score = score + 10 # right side first: compute score + 10 → new value → rebind the nameCreating, using, and reassigning
A variable is born the moment you assign to it — no announcement or declaration beforehand, unlike many other languages. Use a name before assigning it and Python raises a NameError. Reassigning is just moving the label to a new box:
mood = "curious"
print(mood) # curious
mood = "confident"
print(mood) # confident — the old value is simply forgottenA name can even switch to a different type of value — from text to a number, say. Python doesn't mind (this is dynamic typing, coming in lesson 2.2). Just because you can doesn't mean you should — a name that means one thing throughout its life is a kindness to readers.
Try it — watch names move
Predict what each print shows before you run this. The last two lines are the ones that surprise people.
Naming: rules and conventions
The rules (Python enforces these):
- Names use letters, digits, and underscores — but can't start with a digit.
- Names are case-sensitive:
Score,score, andSCOREare three different variables. - The ~35 keywords (
if,for,class, …) are reserved — Python won't let you use them as names.
The conventions (Python won't stop you — professionals will):
- Use
snake_case: lowercase words joined by underscores.total_price, notTotalPriceortotalprice. - Make names say what the value means:
seconds_remaining, notsordata2. - Don't shadow built-ins: naming a variable
printorlistworks — and quietly breaks the realprintandlistfor the rest of your program.
Constants by convention
Python has no true constants — instead, a value that should never change is written in ALL_CAPS, and every Python developer treats it as untouchable:
MAX_ATTEMPTS = 3
PI = 3.14159The language would let you reassign PI. Your teammates would not.
Checkpoint
Answer all three to mark this lesson complete