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.

Code exercise · python

Run the countdown. Trace it by hand once: write down n at each condition check, including the final check that fails.

Quiz

This loop never ends. Why? ```python n = 5 while n > 0: print(n) ```

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.

Quiz

In a loop over range(10), what is the difference between break and continue?

Code exercise · python

Your turn. Find the first number that is 100 or bigger AND divisible by 7, using a while loop: start `n` at 100 and keep adding 1 while `n % 7` is not 0. Print the result.