Variables: giving a value a name
Computer Science · Key Stage 2 · The School
A labelled box
A VARIABLE is a named place to keep a value that might change: a score, a name, how many lives are left. The name stays the same; what is inside can change as often as you like. Programs need them because most useful behaviour depends on something that varies — without a score variable, a game cannot tell you how you did.
Set, change, use
Three things happen to a variable. You SET it to a starting value — score = 0 at the beginning. You CHANGE it — score = score + 1 when something is collected. And you USE it — show the score, or check whether it has reached ten. Forgetting to set it at the start is the commonest bug: the game begins with whatever was left over from last time.
Names are for people
The computer does not care whether you call it score or x. Anyone reading it does, including you next week. livesLeft, playerName and totalScore explain themselves; a, b and temp2 do not. Good names are the cheapest thing you can do to make a program understandable, and they cost nothing to type once.
Trace this by hand, writing the value after every line. `x = 5` (x is 5). `y = x + 3` (y is 8; x is still 5). `x = 10` (x is 10; y is STILL 8, because y was given a value, not a link). `x = x + 1` (x is 11 — the right side is worked out first with the old value, then stored back). That last line looks like nonsense in maths and is the most common line in programming.