The big ideaRead code line by line, use names as clues, and try it with small numbers.
How it works
Read code like a recipe: start at the top and say what each line does, in your own words.
A name in code is a clue, like a label on a box. Good names tell you what each box holds.
Run it by hand with small numbers on paper to see what the code does.
Comments are notes for people, and they can go out of date. Check them against the code, because the code is what runs.
How to read someone else's code.
Example 1: Line by line
The tiny program has four lines: set coins to zero, repeat four times, add three to coins, and say coins.
Line one gives the box coins its start value of zero.
Line two repeats what is inside four times, and line three adds three to coins each time round.
Line four shows what the box holds.
Example 2: Run it by hand
Coins starts at 0, and each trip adds 3.
After trip one it holds 3, after trip two it holds 6, and after trip three it holds 9.
After trip four it holds 12, so the program says 12.
Example 3: Names as clues
Mina opens Teo's code and sees beat count, dance speed and moves.
Those names tell her what each box holds before she reads a single line of the loop.
Example 4: A comment goes out of date
A note beside the loop says four moves per song, but the loop makes five.
Running it by hand with beat count 0, 1, 2, 3, 4 and then 5 finds the mismatch.
The code is what runs, so Mina changes the five to a four and tries it.
Words to know
comment
A note in code for people. The computer skips it.
run it by hand
Work through the code on paper with small numbers.
name
A label for a box, which is a clue to what it holds.
Watch out
Do not skip to the middle. A recipe makes no sense from the middle.
Do not change things and hope. Understand first, because random changes can break more.
Do not trust every comment. The code is what runs.
Change one thing at a time, so it is clear what changed.
Try it
A box starts at 0 and 2 is added three times. What does it hold at the end?
Do you read code from the middle or from the top?
A comment says four moves, but the loop makes five. Which do you trust?
Does the computer read a comment and change the answer because of it?
Should you change one thing or five things at a time?
Answers: 1. 6 · 2. From the top · 3. The code · 4. No · 5. One thing
Try at homeTake a recipe or a board game's rules. With a grown-up, read it one line at a time and say what each line does. Which words are names for things? Run it by hand with a small amount, like one egg, and see if the steps give the result you expect.
For grown-upsRead a recipe or a board game's rules together as if it were code: say what each line does, spot the names for things, and run it by hand with a small amount, like one egg.
Open these notes on screenScan the code, or go to tutorpip.com.