Skip to content
Spark & Whetstonethe grown-up commons

← Reading Code

Reading Code

Three short lessons for grown-ups on reading a short program the way your child learns to: predict what it prints, keep a table of the variables, and follow a loop one turn at a time.

Spark & Whetstone · sparkwhetstone.org/learn/reading-code · CC BY-NC-SA 4.0. Answers are at the end, so you can try each question first.

Lesson 1. Predict, then run

A program is a list of steps the computer follows from top to bottom. A variable is a named box that holds a value, and a line like x = x + 2 means "take what is in x, add 2, and put the result back in x".

Before running anything, predict what it will print. Then check. The gap between your guess and the result is where the learning is.

Try: x = 3, then x = x + 2, then print x.

Question. x = 3, then x = x + 2, then print x. What is printed?

  1. 3
  2. 5
  3. x + 2

Say it back. In your own words: what does x = x + 2 do?

________________________________________________

________________________________________________

Lesson 2. Keep a table

When a program has more than one variable, keep a small table on paper: one column per variable, one row per line. Write the new value each time a line changes it.

For a = 2, b = a × 3, a = b − 1, the table goes: a is 2; b is 6; a becomes 5.

Question. a = 2, then b = a × 3, then a = b − 1. What is a at the end?

  1. 2
  2. 5
  3. 6

Say it back. Say it back: why keep a table of the variables?

________________________________________________

________________________________________________

Lesson 3. One turn at a time

A loop repeats some lines. "For n from 1 to 3: total = total + n" runs three times, with n being 1, then 2, then 3.

Follow it one turn at a time in your table. If total starts at 0: after the first turn it is 1, after the second 3, after the third 6.

Question. total = 0; for n from 1 to 3: total = total + n. What is total at the end?

  1. 3
  2. 6
  3. 0

Say it back. In your own words: how do you follow a loop without running it?

________________________________________________

________________________________________________

At the table: Be the computer

Players: two people, 9 or older. You'll need: paper, a pencil and a short program written out (from TraceForge, or one you make up).

  1. One person writes a five-line program using two variables.
  2. The other predicts what it will print, out loud, before tracing.
  3. Trace it together with a table, one row per line.
  4. Compare the trace with the prediction, then swap roles.

Answers

  1. 5 — x starts at 3, the second line makes it 3 + 2 = 5, so 5 is printed.
  2. 5 — b is 2 × 3 = 6, then a becomes 6 − 1 = 5.
  3. 6 — total goes 0 → 1 → 3 → 6.