Answer: Python Puzzler #32

The answer is D. The program prints:

Time to recharge!
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 2 > 14? No. Is 2 > 7? No. Neither was true, so the else part runs.

Trace table

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

questionanswer
battery > 14False
battery > 7False

The code again

battery = 2
if battery > 14:
    print("Full speed ahead!")
elif battery > 7:
    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.