Skip to content

A Place to Remember

A variable is a named box that holds a value, so a program can keep it, use it, and change it.

The moment the computer shows a value, it forgets it. To do anything interesting, a program needs to remember.

The tool for that is a variable, and almost everything from here on builds on it.

A named box

A variable is a box with a name. You put a value in the box. Later you write the name, and the computer looks inside.

LET score = 0
SHOW "Score: ", score
Output
Score: 0

Two things happened there. LET score = 0 put the value 0 into a box called score. The next line used that box: where you write score, the computer reads whatever sits inside it.

The name is yours to choose. points or total would do as well. Use the same name every time you mean that box.

One thing to unlearn now. That = does not mean “equals” the way it does in maths. LET score = 0 is an instruction: put 0 into the box called score. The difference looks fussy today. In Working It Out it saves you a headache.

Change the box, keep the name

A box you can put a value into is a box you can put a different value into. The name stays. The contents change.

LET score = 0
SHOW "Score: ", score
LET score = 100
SHOW "Score: ", score
Output
Score: 0
Score: 100
StepscoreShown
10
20Score: 0
3100
4100Score: 100

One box, read twice. Steps 1 and 3 put a value in. Steps 2 and 4 look to see what is there now.

That is the whole power of a variable: a name you read whenever you want the value, and write whenever you want to change it. A score that climbs, a life count that falls, a player who moves across the screen — each one is a box with a name, holding a value that changes as the program runs.

When it’s wrong, see why

  • The value never changes. Either you never put a new value in, or you spelled the name differently the second time. score and scor are two different boxes.
  • You get nothing where you expected a value. You used the box before you put anything in it. Fill it first, then use it.
  • The computer does not know the name. You asked for a box it has never seen. Check the spelling against the line that filled it.

What you’ve learnt

  • A variable is a named box that holds a value. It is the program’s memory.
  • You put a value in with LET, and use it by writing its name.
  • The contents change and the name stays. That is how a score climbs.
  • = in LET means put this in the box, not “equals”. Hold on to that.

What’s next

Right now you decide what goes in the box, back when you write the program. In Unit 5 the program asks the person using it.

You can try this idea by storing and changing a greeting in Sinclair BASIC in Meet BASIC. The lesson explains the Spectrum’s own syntax as you use it.