Trace a while loop — quick review
Someone filling a bucket from a tap looks at it before each scoop: if it is not full yet, one more scoop goes in, and then they look again.
A while loop tests its condition before every pass. While the condition is true, it runs the indented body and, when the body reaches its end, goes back to the test; a break ends it sooner. When the condition is false, the program carries on with the first line after the body, and a condition that is false at the first test gives no passes.
Write each name the condition uses, with its value before the loop.
Test the condition with those values. If it is false, skip to the first line after the body.
If it is true, run the body's lines in order and write each name's new value.
Find what can make the condition false at a later test: a line in the body that changes a name it reads, or a new value it reads each time, such as a reply from
input(). If nothing can, and nothing else ends the loop, such as thebreakof this unit's last lesson, the loop will not end on its own.Go back to the test with the new values, and repeat until a test is false or something ends the loop sooner.
Leave out the line that changes the name, and the condition never becomes false. A countdown without seconds = seconds - 1 displays 3 again and again and never ends. Press Control-C, the interrupt key, to stop it; Python stops the program with a KeyboardInterrupt.
The other slip is the edge of the condition. seconds > 0 stops before 0 is displayed, and seconds >= 0 displays 0 as well. Trace the last two tests to see which values get a pass.