Skip to content

ProgrammingPython on a Raspberry Pi

Tracing Code by Hand

Follow a program one line at a time, writing down every variable, to know what it will do.

Not started Jump to practice

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 + 25

What is speed at the end?
  1. range(4) gives i = 0, 1, 2, 3: four passes.
  2. 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
  1. Pass 1: d = 35, steps = 1.
  2. Pass 2: d = 20, steps = 2.
  3. Pass 3: d = 5, steps = 3.
  4. Now d > 10 is false, so the loop stops.

Answer: d = 5, steps = 3.

A trace table for the while loop.
passd befored aftersteps
150351
235202
32053

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.

Practice

Pass with 3 right answers, the last 2 in a row. Each right answer earns 2 XP.

Loading practice…

Builds on

Leads to

Sources and further reading