Before you trust a robot's program, run it in your head. Professionals do this all the time; it is the fastest way to find a bug.
Key idea
To trace code, go one line at a time and keep a table of every variable. Each time a line changes a variable, write the new value. For a loop, write one row per pass.
Worked example: Trace a loop
speed = 0
for i in range(4):
speed = speed + 25What is
speed at the end?- range(4) gives i = 0, 1, 2, 3: four passes.
- speed: 0 β 25 β 50 β 75 β 100.
Answer: 100.
Worked example: Trace a while loop
d = 50
steps = 0
while d > 10:
d = d - 15
steps = steps + 1- Pass 1: d = 35, steps = 1.
- Pass 2: d = 20, steps = 2.
- Pass 3: d = 5, steps = 3.
- Now d > 10 is false, so the loop stops.
Answer: d = 5, steps = 3.
| pass | d before | d after | steps |
|---|---|---|---|
| 1 | 50 | 35 | 1 |
| 2 | 35 | 20 | 2 |
| 3 | 20 | 5 | 3 |
Why it works
A robot's bugs often hide in the first or last pass of a loop. Writing every pass down catches them before the robot drives off the table.
Common mistake
Guessing what a loop does from its shape. Write the table; it takes a minute and it is never wrong.
Hands-on: your first Raspberry Pi program
Getting started
- \$0: Python on any computer, or a free online Python editor.
- About \$5 to \$10: a Raspberry Pi Pico with MicroPython, plus an LED and resistor from the starter kit.
- About \$60 to \$100: a Raspberry Pi single-board computer with a power supply and memory card, for camera and vision projects later.
Blink the Pico's built-in LED. Then change the program to blink faster each time through the loop, and trace it on paper before you run it.