Glossary

While Loop

The while loop repeats a block of code as long as its condition evaluates to true. The syntax is while condition: followed by an indented body. The condition is checked before each iteration; if it is false from the start, the body never executes. A while True: loop runs indefinitely until a break statement is encountered.

While loops are less common than for loops in Python because most iteration is over collections (where for is more natural). The main use cases for while are: waiting for a condition to change (polling), reading input until a sentinel value, implementing algorithms that do not iterate over a collection (like binary search or Newton's method), and interactive loops (menus, prompts).

Like for loops, while loops support break (exit the loop immediately), continue (skip to the next iteration), and an optional else clause (runs if the loop exits normally, without break). A common beginner mistake is creating an infinite loop by forgetting to update the variable that controls the condition. Python's REPL and development servers use KeyboardInterrupt (Ctrl+C) to break out of accidental infinite loops.

Related terms: For Loop

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.