Variables
Names that refer to values.
3 minute read
Big idea
A variable is a name that refers to a value. = attaches the name on the left to the value on the right.
The idea
age = 20
name = "Ada"
Read = as "is now": "age is now 20". It isn't the maths equals sign — it's an instruction, and it runs right to left: work out the value on the right, then attach the name on the left.
Once a name exists, use it anywhere you'd use the value:
name = "Ada"
age = 20
print(name, "is", age)
print(age + 1)output
Ada is 20
21Run and edit it in the app.
There's no "type" to declare, unlike C's int age = 20;. Python works out what kind of value it is by looking at it.
Changing a variable
A variable can be pointed at a new value any time. The old value is forgotten:
score = 10
score = score + 5
score = score * 2
print(score)What does it print? Show the answer
30Run and edit it in the app.
score = score + 5 looks impossible in maths, but in Python it means "work out score + 5 (that's 15), then make score refer to that".
Names are labels, not boxes
In Python, a variable is a label stuck on a value. Two names can be stuck on the same value:
a = 7
b = a # b now refers to the same 7
a = 100 # a is moved to a new value; b still refers to 7
For numbers and text this never surprises you. It matters later, with lists — keep this picture in mind.
Watch it
Naming rules
- Letters, digits, and
_only — no spaces or dashes. - Can't start with a digit:
2nd_placeis an error,place_2is fine. - Case matters:
Ageandageare different variables. - Can't be a keyword Python reserves, like
if,for,class,True.
The Python habit is snake_case: lowercase words joined by underscores — total_price, first_name.
2nd_place = "Grace"
print(2nd_place)output
GraceRun and edit it in the app.
Several at once
x, y, z = 1, 2, 3 # x is 1, y is 2, z is 3
a = b = 0 # both start at 0
After a = 5, b = a, a = 9 — what is b?
Think of it like
A name tag. Writing age = 20 sticks the tag "age" on the number 20. Later age = 21 peels it off and sticks it on 21.
Key terms
- Variable — A name that refers to a value.
- Assignment — Attaching a name to a value with
=. - snake_case — The Python naming style:
lower_case_with_underscores.
Check yourself
What does age = 20 do?
Which is a valid variable name?
score = 4, then score = score * 3. What is score?