bhylu.com

Advertisements

While Loops

A while loop repeats while a condition remains true. Use it when the number of steps depends on changing state rather than a known iterable.

Understand the idea

Make progress toward a stopping condition on every relevant path. break exits the loop, while continue skips to the next condition check. If continue bypasses the update that would eventually stop the loop, the program can run forever. Keep a small trace of state values when debugging.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

remaining = 3
while remaining > 0:
    print(remaining)
    remaining -= 1
print("Done")

Read the result

The output counts 3, 2, 1 and then Done.

Try one change

Change the countdown to stop at zero inclusively and verify the final number.