Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Statements and Keywords

The while statement

Reference for Python's while statement: repeat while a condition is true, sentinel loops, while True with break, the loop else clause and infinite-loop mistakes.

A while loop repeats its body as long as a condition stays true. The condition is checked before each pass, so the body may run zero times. Use while when you do not know in advance how many repetitions you need: reading until input ends, retrying an operation, running a game loop or converging on a result.

When you can say "for each item in ...", a for loop is the better tool. A while loop must change something that eventually makes the condition false, or exit with break.

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

Try it

Python Counting and converging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python while True, break and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
while condition:
    body
else:
    after_normal_exit
Part Description
condition Any expression, tested by truthiness before every iteration.
else Optional. Runs once when the condition becomes false. It is skipped if the loop ends through break (or an exception or return).

Usage notes

  • Infinite loops. Forgetting to update the variable in the condition makes a program hang. while True: is intentional only when the body has a reachable break or return.
  • break and continue work as in for: break leaves the loop and continue jumps to the next condition check. Be careful that continue does not skip the line that updates the counter.
  • The condition is re-evaluated each time, so make it cheap, and remember that it can have side effects (while (line := f.readline()):).
  • No new scope. Variables assigned in the body remain available after the loop.
  • Floating-point conditions are fragile. while x != 1.0 may never become false; use a tolerance (abs(x - target) > 1e-9) or math.isclose().
  • Choose for when possible. for i in range(n) is shorter and safer than a manual counter with while.
  • Sentinel and event loops (read until empty, process a queue until it is empty, wait for a flag) are the natural uses: while queue: is the idiomatic "while not empty" test.
  • In the browser runner, an infinite loop stops after the time limit. In a real program use Ctrl+C (KeyboardInterrupt) to interrupt it.