TwiddleLab / Code / How a Programmer Thinks
Variables Are Boxes
What you will learn
- A variable is a named box that holds one value.
- = means put: work out the right side, then put the result in the box on the left.
- So x = x + 1 takes x out, adds 1 and puts it back. Following this line by line is tracing.
How the lesson goes
In math, x = x + 1 is impossible. Programmers write it every day.
What ends up in box x? Drag your bet into the box.
Run it and watch the box.
Press Step. The glowing line runs next.
Before each line runs, tap the box it will change.
Build a streak.
What you just did has names.
A variable is a named box that holds one value. Here the box is called x.
= is assignment. It does not mean "equals". It means: work out the right side, then put the result in the box on the left.
Following code line by line and keeping track of every box is tracing. You just did it.
Be the machine. Trace these four lines.
For each glowing line, drag the new value into the box it changes. Then press Check.
Make coins end at exactly 10.
Put the three lines in order, then press Run.
Swap puzzle: make a hold 8 and b hold 3.
A box holds one value, so you need a spare box called temp. Fewest lines wins. Par is 3.
Design your hero: tune the fight.
Your hero takes two hits and drinks one healing kit. Set the hit and kit so the hero ends at exactly 50 health.
What is in box a at the end?
Speed round: call the box.
Three tiny programs. Pin what ends up in the box before the time bar runs out.
Previous lesson: Instructions, Exactly · Next lesson: Decisions: if · Part of the course: How a Programmer Thinks
Lessons are interactive and need JavaScript. Turn it on to play them.