If you remember one idea from programming, make it this one. A variable is a name for a piece of information that a program can remember and use later.
The labelled box
Imagine a box on a shelf with a label on the front. The label says score. Inside the box is the number 10.
You can:
- Look inside the box to see what's there.
- Put something new inside, replacing the old thing.
- Use what's inside in a sum.
The label stays the same, but the contents can change. That is exactly what a variable is.
In Python
score = 10
print(score)The first line makes a box called score and puts 10 in it. The second line looks in the box and shows what's there. The = sign does not mean "equals" like in maths. Read it as "put this value in the box."
Now change what's inside:
score = 10
score = score + 5
print(score)This prints 15. Python looks at what's in score (10), adds 5, and puts the answer back in the same box.
Variables can hold words too
pet = "dog"
age = 4
print(pet)
print(age)Text goes inside quotation marks. Numbers don't.
Why bother?
Without variables, a game could not remember your points or your lives. A program couldn't greet you by name. Variables are how a program keeps track of anything that changes.
Three common mix-ups
1. Thinking two variables stay linked.
a = 5
b = a
a = 10
print(b)This prints 5, not 10. b = a copies the number at that moment. It does not tie the two together. Each variable is its own box.
2. Spelling the name differently.
player_name = "Maya"
print(player_nam)This causes an error because player_nam was never created. Python doesn't guess what you meant.
3. Invalid names. A name can't start with a digit (1st_place fails) and can't contain spaces. Use underscores: high_score.
Try it yourself
Ask your child to:
- Make a variable called
favourite_animaland print it. - Make a variable called
livesset to 3, then subtract 1 and print it. - Predict what each line will do before running it.
Predicting first, then checking, is one of the most powerful ways to learn.
Next steps
Once variables feel natural, if statements let programs make decisions based on what's in them. You can also read a full worked lesson, free, in the Variables lesson.