Python While Loops
Python · Loops
Theory
A while loop repeats its block as long as its condition stays truthy. Python checks the condition before every pass: if true, the body runs and control jumps back to the check; if false, the loop ends and execution continues after it. In the example, count starts at 0, is printed, and is increased by 1 each pass; when count reaches 5 the test count < 5 is False, so the output is 0 to 4. If the condition is false at the start, the body never runs at all.
The body must eventually make the condition false, usually by updating a variable. Forget count += 1 and the loop never stops: an infinite loop (stop it with Ctrl+C or the stop button in Jupyter). Deliberate infinite loops, while True:, are fine when the body uses break to exit, for example when reading input until the user types quit. break leaves the loop immediately, and continue skips to the next condition check.
Why we use it
Some repetition has no fixed count: retry until a request succeeds, read until the file ends, keep asking until the input is valid. while repeats based on a condition, not on a collection.
When to use it
Use while when you do not know in advance how many passes are needed. When looping over items of a collection or a known range, prefer for, which cannot forget to update its counter and so cannot become accidentally infinite.
How it works
- count = 0
- Is count < 5 true? Yes: Run the body. No: Exit the loop.
- Body: print(count)
- Body: count += 1 (moves toward ending the loop)
- Jump back to the condition check
- After the loop: printed 0, 1, 2, 3, 4
Syntax
while condition:
...Example
count = 0
while count < 5:
print(count)
count += 1Key points
- Risk of infinite loops if the condition never becomes false
- The condition is checked before each pass, so the body may run zero times
- Update the loop variable inside the body
- while True: with break is a common pattern for 'repeat until'
- break exits early, continue skips to the next iteration