A box with a label ๐งฎ
You already know loops, events and if-then blocks. Now meet the variable.
Picture a box with a label on it. The box holds one value, such as a number. The program can look inside the box and can swap what's inside.
- set inside to 0 empties the box and drops a 0 in.
- change inside by 1 adds 1 to what's there.
- change inside by -1 takes 1 away.
Games use variables for points, lives and time left. Room 12 is helping at their school's winter fun day. The warming tent safely holds 12 people, so they want a counter that tracks how many people are inside. Their tool is a pocket-sized coding board, such as a micro:bit, with an A button and a B button.
Worked exampleTrace the tent counter
The program starts. Then the buttons are pressed in this order: A, A, A, B, A, B, B, B. What is on the screen after the last press?
- Start: inside = 0.
- A, A, A: 0 โ 1 โ 2 โ 3.
- B: 3 โ 1 = 2. A: 2 + 1 = 3.
- B, B, B: 3 โ 2 โ 1 โ 0.
- After the last B, inside = 0, so the if-then is true and the screen shows "Empty".
The final value of inside is 0, so "Empty" appears. Everyone who went into the tent has come out.