Computer science
Variables & values
Labelled drawers for values: the memory of every program.
What you need first
Your phone knows how many steps you've walked today. Your favourite game remembers your score. For a program to remember something, it needs a named place where the value lives. That's exactly what a variable is, and here you'll learn how it works.
A drawer with a label
Picture a variable as a labelled drawer. The label shows the name, inside the drawer lies the value. With x = 5 you put the number 5 into the drawer named x, which is called assigning. The equals sign is a command here, not a statement about equality: put the value on the right into the drawer on the left. If you ask for x later, the program looks into the drawer and finds the 5. If you then assign x = 9, the 5 is taken out and the 9 is put in: a drawer only ever holds the newest value.
x = 4
x + 3 = 7
2 · x = 8
x has the same value everywhere.
Calculating with variables
The best thing about variables: you can calculate with them without knowing the value. The expression x + 3 means: take whatever is in x right now and add 3. If x holds a 5, you get 8. If it holds a 10, you get 13. The calculation stays the same, only the drawer's contents change. Even score = score + 1 is allowed: first the old value is read, then 1 is added, and the result goes back into the drawer. It works the same with minus: balance = balance - 8 reads the old amount, subtracts 8 and puts the result back in.
Good names pay off
The computer doesn't care about the name, but you do. A program full of variables like x, y, and z is like a cabinet full of drawers without labels: after a week you won't remember what's where. Names like score, age, or balance tell you immediately what's inside the drawer. Good names make programs easier to read and mistakes easier to find.
Exercises
0 of 6 solvedTime to try it yourself. You can't break anything, every attempt counts.
What is a variable?
A program runs: x = 5. What value is in x afterwards?
A program runs: x = 4, then x = 9. What value is in x now?
The program runs score = score + 5. Put the steps in the correct order.
- 1The result is put back into the drawer
- 25 is added to this value
- 3The old value is read from the drawer
x holds the value 6. What is x + 3?
Match each variable name to what sensibly lives inside it.
Where this leads