Course outline · 0% complete

0/32 lessons0%

Course overview →

while, break, continue

lesson 5-2 · ~11 min · 14/32

while: repeat as long as a condition holds

Menus that redisplay until the user picks quit, games that run until somebody wins, retries until a network call succeeds: none of these know their pass count in advance, so for cannot express them. That open-ended territory belongs to while.

A for loop knows in advance how many passes it will make. A while loop does not: it keeps running its body while its condition stays True, checking before every pass.

n = 3
while n > 0:
    print(n)
    n = n - 1
print("liftoff")

Something in the body must move the condition toward False. Forget the n = n - 1 and the condition never changes: an infinite loop that runs forever. If that happens, stop the program and find the line that should have made progress.

Use for when you know the items or the count. Use while when you only know the stopping condition, like keep asking until the input is valid.

Tracing a countdown

The body prints and then decrements, so the condition sees a smaller value each time it is checked.

n = 3
while n > 0:
    print(n)
    n = n - 1
print("liftoff")

Output

3
2
1
liftoff

Following the checks by hand is the fastest way to trust a while loop. The condition is tested with n at 3, 2, and 1, all of which pass, and each pass prints and then reduces n. The fourth check finds n at 0, which fails n > 0, so the body is skipped entirely and control moves to the unindented print. Note that the failing check still happens, and that four checks produced only three lines of loop output.

This loop never ends because nothing in the body changes n.

n = 5
while n > 0:
    print(n)

The condition re-examines the same unchanged 5 on every pass, so it stays True forever and the program prints without stopping. A while loop only terminates when its body moves some value toward the failing case, and the missing line here is n = n - 1.

That makes the debugging strategy specific rather than vague. When a program hangs, find the variable the condition depends on and check whether the body actually changes it, since the fault is usually a missing update or an update sitting inside an if that never runs.

break and continue

Two statements steer a loop from inside its body:

  • break exits the loop immediately, skipping all remaining items.
  • continue skips the rest of this pass and jumps to the next item.
for i in range(1, 10):
    if i % 2 == 0:
        continue   # skip even numbers
    if i > 7:
        break      # stop entirely once past 7
    print(i)

This prints 1, 3, 5, 7. The evens are skipped by continue, and when i reaches 9 the break ends the loop before printing. Both work in for and while loops alike.

In a loop over range(10), break exits the loop while continue skips to the next item.

break abandons the loop completely, so no further items are visited no matter how many remain. continue abandons only the current pass, jumping straight to the next item and leaving the loop itself running.

Neither one restarts anything. The loop keeps its place in the sequence, so a continue on item 3 resumes at item 4 rather than returning to the beginning. Choosing between them comes down to whether the remaining items still matter: a search that has found its answer wants break, while a filter that is ignoring one bad row wants continue.

Searching upward for the first value satisfying a rule is a natural fit for while, because the number of passes is unknown before the loop starts.

n = 100
while n % 7 != 0:
    n = n + 1
print(n)

Output

105

The condition states what must remain true to keep going, so it tests for not yet divisible, n % 7 != 0. Writing the goal condition instead would invert the logic and skip the loop entirely. Starting at 100, the loop advances through 101, 102, 103, and 104, and stops as soon as n reaches 105, since 105 divided by 7 leaves no remainder. The print sits outside the loop so it reports the value that satisfied the search.