Python While Loops: A Comprehensive Guide
Master Python while loops: syntax, break, continue, else clause, nested loops, infinite loops, and practical examples with clear explanations.
A while loop runs a block of code repeatedly as long as a condition is True. Unlike a for loop, which iterates over a known sequence of items, a while loop is the right choice when you don't know in advance how many iterations you need — for example, when reading user input, draining a queue, or retrying an operation until it succeeds.
This chapter covers:
- Basic syntax and how the condition is evaluated
break— exit the loop earlycontinue— skip to the next iteration- The
elseclause — code that runs when the loop ends normally - Nested
whileloops - The
passplaceholder - Infinite loops and how to avoid them
- When to choose
whilevsfor
Basic syntax
while condition:
# block executed while condition is TruePython evaluates condition before each iteration. If it is True, the indented block runs. When the block finishes, the condition is checked again. The loop exits as soon as the condition evaluates to False.
Counting from 1 to 5
Output:
1
2
3
4
5Here i starts at 1. After each print, i increases by 1. When i reaches 6, the condition i <= 5 becomes False and the loop stops.
The counter variable must be updated inside the loop. Forgetting i += 1 (or an equivalent update) means the condition never becomes False and you get an infinite loop.
Countdown example
count = 5
while count > 0:
print(count)
count -= 1
print("Liftoff!")Output:
5
4
3
2
1
Liftoff!Code after the while block runs once the loop has finished — in this case print("Liftoff!") is not inside the loop.
Looping until a list is empty
Any object that has a boolean value works as a condition. An empty list is falsy, so you can drain a list naturally:
stack = [1, 2, 3]
while stack:
print(stack.pop())Output:
3
2
1while stack is shorthand for while len(stack) > 0. Once the list is empty, it is falsy and the loop ends.
The break statement
break exits the loop immediately, regardless of the condition.
Output:
0
1
2
3
4When num equals 5, break fires and the loop terminates — 5 through 9 are never reached.
When to use break: stop a search as soon as you find a match; abort a loop when an error condition arises; exit a menu loop when the user chooses "quit".
The continue statement
continue skips the rest of the current iteration and jumps straight back to the condition check.
i = 0
while i < 8:
i += 1
if i % 2 == 0:
continue
print(i)Output:
1
3
5
7When i is even, continue skips print(i) and the loop goes back to evaluate the condition with the updated i.
Important: increment the counter before the continue check, not after. If i += 1 were placed after continue, i would stay even forever and the loop would run indefinitely.
The else clause
Python's while loop supports an optional else block. It runs only if the loop ended naturally — i.e., the condition became False — and is skipped if the loop was exited via break.
Normal completion
i = 1
while i <= 3:
print(i)
i += 1
else:
print("Done!")Output:
1
2
3
Done!Loop interrupted by break
i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 1
else:
print("No break")Output:
1
2"No break" is never printed because break terminated the loop before the condition could become False.
Practical use: linear search
The else clause is especially useful for search patterns. The else block runs only when the target was not found:
numbers = [4, 7, 2, 9, 1]
target = 9
i = 0
while i < len(numbers):
if numbers[i] == target:
print("Found", target, "at index", i)
break
i += 1
else:
print(target, "not found")Output:
Found 9 at index 3Nested while loops
A while loop can contain another while loop inside it. The inner loop completes all its iterations for every single iteration of the outer loop.
row = 1
while row <= 3:
col = 1
while col <= 3:
print(row * col, end=" ")
col += 1
print()
row += 1Output:
1 2 3
2 4 6
3 6 9 Gotcha: a break inside the inner loop exits only the inner loop. To exit both loops at once, use a flag variable or restructure the code into a function and return.
The pass statement
pass is a no-op placeholder. Use it when a while loop is syntactically required but the body is not yet implemented:
i = 0
while i < 3:
pass # TODO: add logic later
i += 1Without pass, Python would raise an IndentationError because an empty block is invalid syntax.
Infinite loops
An infinite loop runs forever because its condition never becomes False. This is almost always a bug — but there are intentional uses too.
Accidental infinite loop
# WARNING: this loop never ends — do not run
i = 1
while i <= 5:
print(i)
# forgot to increment iWithout i += 1, i stays 1, the condition is always True, and the loop runs until you stop the program manually (Ctrl+C).
Intentional infinite loop with break
# WARNING: intentional infinite loop — requires Ctrl+C to stop outside an app
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print("You typed:", answer)while True is a deliberate idiom for "keep going until explicitly stopped." You must always have a break (or a return) somewhere inside, or the program will hang.
See the Python User Input chapter for more patterns involving interactive loops.
While loops vs for loops
| Situation | Prefer |
|---|---|
| You know the number of iterations or have a sequence | for |
| You loop until a condition changes | while |
| You need to read input until the user quits | while True + break |
| You want index and value from a list | for + enumerate() |
| You want to drain or consume a data structure | while |
Use for when you can; switch to while when the end condition is dynamic or unknown at the start of the loop.