Sub topic 1
How a while loop works
A while loop repeats a block of code as long as a condition is true. This chapter builds the working model: how Python evaluates the condition, what has to change inside the body, and which mistakes keep a loop from ending.
Prerequisites
This chapter assumes you already know:
- How to create variables and assign values to them.
- Comparison operators (
<,==,!=) and boolean operators (and,or,not). - How
ifstatements work, and that Python uses indentation to mark a block. - Basic use of
printandinput.
You do not need to know for loops yet. A later chapter compares them with while.
The shape of a while statement
A while statement has a header and a body.
n = 3
while n > 0:
print(n)
n -= 1
print("Liftoff")The output is:
3
2
1
LiftoffThe header is the line while n > 0:. It contains the keyword while, a condition, and a colon. The body is the indented block under it. The line print("Liftoff") is not indented, so it is not part of the loop. It runs once, after the loop ends.
Python runs the statement like this:
- Evaluate the condition.
- If the condition is true, run the whole body once, then go back to step 1.
- If the condition is false, skip the body and continue with the next statement after the loop.
Two consequences follow from this model.
- The condition is checked before the first pass. If it is false at the start, the body runs zero times.
- The condition is checked only between passes. If the condition becomes false in the middle of the body, Python still finishes the rest of that pass.
The second point surprises many learners:
n = 3
while n > 0:
n -= 1
print("after decrement:", n)
print("still in the same pass")When n reaches 0 inside the body, both print calls still run for that pass. Only then does Python check n > 0 again and stop.
A loop that runs zero times
count = 10
while count < 5:
print("This never prints")
print("Done")The condition 10 < 5 is false on the first check, so the body is skipped. Only Done is printed. A zero-iteration loop is normal, and it is often the correct behavior for empty input.
What counts as a true condition
The condition does not have to be a comparison. Python accepts any expression and converts its result to a boolean. This conversion is called truthiness.
Most values are truthy. The following are falsy, meaning they count as false:
| Value | Type |
|---|---|
| `False` | bool |
| `None` | NoneType |
| `0`, `0.0` | numbers |
| `""` | empty string |
| `[]`, `()`, `{}`, `set()` | empty containers |
Everything else is truthy. A common use is looping while a list still has items:
tasks = ["email", "report", "review"]
while tasks:
current = tasks.pop()
print("Working on", current)
print("All tasks done")tasks is truthy while it has at least one element. Each pop() removes the last item, and when the list is empty the condition becomes false. This prints review, report, then email.
Writing while tasks: is the usual Python style. Writing while len(tasks) > 0: works but is longer. Use the explicit form when it makes your intent clearer, for example when the value could be 0 or None and you need to tell those cases apart.
Combining conditions
You can combine tests with and, or, and not. Python evaluates and and or from left to right and stops as soon as the result is known. This is called short-circuiting, and it makes some guards safe:
items = [4, 8, 15]
i = 0
while i < len(items) and items[i] < 10:
print(items[i])
i += 1If i equals len(items), the first test is false, so Python never evaluates items[i]. Reversing the two tests would raise an IndexError on the last check. The output is 4 and 8. The loop stops at 15 because 15 < 10 is false.
Changing state so the loop can end
A loop condition depends on some state: a variable, a collection, a file, the clock. For the loop to end, something in the body must change that state so the condition eventually becomes false.
A well-formed while loop has four parts:
- Initialization. Set up the state before the loop (
n = 3). - Condition. Test the state (
n > 0). - Body work. Do the useful thing (
print(n)). - Update. Move the state toward making the condition false (
n -= 1).
If you forget the update, the condition never changes, and the loop never ends.
n = 3
while n > 0:
print(n)
# missing n -= 1: this prints 3 foreverThe update does not have to be a counter. It can be anything that moves the loop toward its end:
- Removing items from a list.
- Reading the next line from a file.
- Halving a number.
- Waiting for a timer to run out.
Here is a loop where the state changes by division:
value = 100
steps = 0
while value >= 1:
value //= 2
steps += 1
print("Halved", steps, "times")value goes 100, 50, 25, 12, 6, 3, 1, 0. The loop ends when it reaches 0, after 7 halvings, and prints Halved 7 times.
Check that the update moves in the right direction
The update must move toward the stopping point, not away from it. This loop never ends because n grows while the condition asks for it to be smaller than 10 and the step is mistaken:
n = 5
while n > 0:
n += 1 # wrong direction: n only gets biggerA quick check before you run a loop: pick the condition, pick the update, and ask whether repeating the update enough times must make the condition false. With floating-point numbers this also needs care. A condition such as x != 1.0 with x += 0.1 may never be exactly equal to 1.0, so prefer < or <= over == and != when stepping by fractions.
Infinite loops and while True
A loop that never ends is an infinite loop. Sometimes it is a bug. Sometimes it is exactly what you want, for example a server that keeps waiting for requests, or a prompt that keeps asking until it gets a good answer.
For a deliberate infinite loop, use the constant True as the condition and leave from inside the body with break:
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")The condition True is never false, so the header never ends the loop. The if inside the body decides when to stop. If the user types secret on the second try, the output is Done after 2 attempt(s). If they never get it right, the loop stops after the third attempt.
This pattern fits cases where the stop event happens in the middle of the body, after you have read input or called a function. Without while True, you would have to duplicate the input line before the loop and again at the end of the body.
# Without while True: the input call appears twice
answer = input("Password: ")
while answer != "secret":
answer = input("Password: ")Both versions work. Use while True when the duplicated setup is awkward or the stop condition is complex.
Leaving a loop early with break
The break statement ends the nearest enclosing loop immediately. Python skips the rest of the body, does not check the condition again, and continues with the first statement after the loop.
numbers = [3, 8, -1, 5]
i = 0
while i < len(numbers):
if numbers[i] < 0:
print("Found a negative number at index", i)
break
i += 1
print("Search finished")This prints Found a negative number at index 2 and then Search finished. The loop stops at index 2, so 5 is never examined.
Use break when:
- You are searching and have found the item.
- An error or end-of-data signal makes further passes pointless.
- A
while Trueloop has reached its stop event.
Keep the number of break statements in one loop small. With one or two, the exit points are easy to see. With many, readers must trace every path to know when the loop ends.
Skipping an iteration with continue
The continue statement ends the current pass and jumps back to the condition check. The rest of the body for that pass is skipped, but the loop itself keeps going.
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)This prints 1, 3, 5, 7, 9. When i is even, continue skips the print. The increment i += 1 comes before the continue, so i still changes on every pass.
The classic continue bug
Where you put the update matters. If the update comes after continue, the skipped passes never run it:
i = 0
while i < 10:
if i % 2 == 0:
continue # bug: i is never incremented, so this loops forever
i += 1At the start i is 0, which is even, so continue runs. Python jumps back to the condition, which is still true, and i is still 0. The program is stuck.
There are two common fixes:
- Move the update to the top of the body, before any
continue, as in the working example above. Remember to adjust the logic if the update changes which values you test. - Put the update inside the branch that uses
continue:
i = 0
while i < 10:
if i % 2 == 0:
i += 1
continue
print(i)
i += 1The first fix is simpler and harder to break when you edit the loop later.
Common mistakes and how to avoid them
| Mistake | Symptom | Fix |
|---|---|---|
| No update to the loop state | Loop never ends | Add a statement that moves state toward the stop condition |
| Update in the wrong direction | Loop never ends | Check the sign of the step against the condition |
| Update placed after `continue` | Loop never ends on some values | Move the update above `continue` |
| `==` or `!=` with floats | Loop skips past the target and never ends | Use `<`, `<=`, `>`, or `>=` |
| Off-by-one condition (`<` vs `<=`) | One pass too many or too few | Test the first and last values by hand |
| Changing a list while looping over its index | Items skipped or `IndexError` | Loop with `while items:` and `pop()`, or build a new list |
| Forgetting a stop path in `while True` | Loop never ends | Make sure at least one `break` or `return` can be reached |
Debugging a stuck loop
If a program seems frozen, a while loop is a likely cause. Press Ctrl+C in the terminal to raise KeyboardInterrupt and stop it. The traceback shows the line that was running, which usually points to the loop.
Then add a print of the loop variables at the top of the body:
n = 5
while n > 0:
print("n is", n)
n += 1
if n > 10:
break # temporary safety limit while debuggingSeeing n rise from 5 shows that the update goes the wrong way. A temporary pass limit like the one above keeps the program from running forever while you investigate. Remove it when the bug is fixed.
Where to go from here
The ideas in this chapter fit together as one model. The condition is checked before every pass. The body must change the state the condition reads. break leaves the loop at once, and continue returns to the condition check. Later chapters build on this model with the else clause, nested loops, choosing between while and for, and the walrus operator.
Exercise
What does this code print, and how many times is the condition n < 3 evaluated?
n = 0
while n < 3:
n += 1
if n == 2:
continue
print(n)
Show answer
It prints 1 and 3. The condition is evaluated 4 times: with n = 0, 1, 2, and 3. On the pass where n becomes 2, continue skips the print, but n += 1 comes before it, so the loop still advances. When n reaches 3, the condition is false and the loop ends.
Exercise
This loop is meant to print the even numbers from 2 to 10, but it never ends. Find the bug and fix it. i = 2 while i <= 10: if i % 2 == 1: continue print(i) i += 1
Show answer
The loop starts with i = 2, so it prints 2 and moves on, but if i ever becomes odd, continue skips the update and i never changes. Here the real problem is the design: the update only runs on the even path. A fix is to move the update before the check or to step by 2. For example: i = 2, then while i <= 10: print(i) and i += 2. This prints 2, 4, 6, 8, 10 and always advances.
Exercise
Rewrite this loop using while True and break so that the input call appears only once. word = input("Word: ") while word != "quit": print("You typed", word) word = input("Word: ")
Show answer
while True: word = input("Word: ") if word == "quit": break print("You typed", word)