Answer: Python Puzzler #145

The answer is B. The program prints:

Slow and steady.
What the program prints
Checked by running the program for real.

Why?

Python checks the conditions from the top and runs the first one that is true. Is 16 > 17? No. Is 16 > 5? Yes.

Trace table

A trace table follows the program step by step. Here’s this one:

questionanswer
battery > 17False
battery > 5True

The code again

battery = 16
if battery > 17:
    print("Full speed ahead!")
elif battery > 5:
    print("Slow and steady.")
else:
    print("Time to recharge!")

Try it: change one number in the program and predict the new output before you run it.