Python Puzzler #3982

Python Puzzlers card for the topic decisions

Challenge type: Python Puzzlers  ·  Difficulty: ★★★★★ Super tricky  ·  Topic: decisions

Read this Python program carefully. Don’t run it yet! Can you work out exactly what it prints?

for number in range(1, 9):
    if number % 3 == 0:
        print("Zap")
    else:
        print(number)

Choose an answer

ChoiceOutput
A
1
2
Zap
4
5
Zap
7
B
1
2
3
4
5
6
7
8
C
Zap
2
3
Zap
5
6
Zap
8
D
1
2
Zap
4
5
Zap
7
8
Need a hint?

Pretend you are the computer. Go through the program one line at a time, and write down every variable’s value on paper as it changes. Programmers call this a trace.

Grown-ups: Reading code and predicting what it does is a key programming skill. Once your child has chosen an answer, run the code in IDLE together to check.

For teachers and grown-ups

Skills practised: Code reading, tracing variables, and understanding Python syntax.

The big idea: Predicting a program's output before running it builds a solid mental model of how code works.

Questions to ask:

  • What is the value of each variable after every line?
  • Which line decides the output?
  • What small change would make it print something different?

Take it further: Children use a trace table on paper for the code, then run it in IDLE to check, and change one value to make a new puzzle for a friend.