Python ยท Chapter 13 of 45

Python While Loop

`while` repeats a block as long as a condition stays true. Use it when you don't know in advance how many times to loop.

Always make sure the condition eventually becomes false, otherwise you get an infinite loop.

break and continue

`break` exits the loop entirely. `continue` skips to the next iteration.

else on a loop

A `while` (or `for`) loop can have an `else` block that runs only if the loop finished WITHOUT `break`.

Example 1 (python)
n = 1
while n <= 3:
    print(n)
    n += 1
Output
1
2
3

Loops while n is 1, 2, then 3.

Example 2 (python)
i = 0
while True:
    i += 1
    if i == 3:
        break
print("stopped at", i)
Output
stopped at 3

break exits an infinite loop when a condition is met.

Key points

  • Runs while the condition is truthy.
  • Update the loop variable inside the body.
  • `break` exits; `continue` skips.
  • Beware of infinite loops.
๐Ÿ’ก Note: If you know how many times to repeat, use `for` โ€” it's clearer than `while` with a counter.

๐Ÿ“ Quick Quiz

1. What exits a while loop immediately?

2. What does `continue` do?

3. A `while True:` loop needs: