Sub topic 5
Leaving a loop early with break
This chapter assumes you can write a basic while loop and update its variable so the condition eventually becomes false. It also assumes you know if statements, comparison operators, and input. Here you will learn what break does, the loop shapes it makes possible, and the edge cases that surprise people.
What break does
A while loop normally ends only when its condition is checked and found false. The break statement adds a second way out. When Python runs break, it stops the innermost loop immediately. It skips the rest of the loop body and does not check the condition again. Execution continues with the first statement after the loop.
n = 1
while n <= 100:
if n * n > 50:
break
n += 1
print("First n with n*n > 50:", n)The condition n <= 100 would allow 100 passes. The break ends the loop at n = 8, because 8 × 8 = 64 is the first square above 50. The program prints First n with n*n > 50: 8.
A break is almost always inside an if. A bare break at the top level of a loop body would end the loop on the first pass, and the code after it would never run.
Two exits, two questions
With break, a loop can end for two different reasons: the condition went false, or a break ran. After the loop, you often need to know which one happened. The usual approach is to record the answer in a variable before you break.
numbers = [4, 8, 15, -3, 16]
i = 0
found = None
while i < len(numbers):
if numbers[i] < 0:
found = i
break
i += 1
if found is None:
print("No negative numbers")
else:
print("First negative at index", found)This prints First negative at index 3. If the list had no negative number, found would stay None and the first message would print. The else clause on a loop can also detect whether a break happened. A later chapter covers it, so this chapter uses a variable.
The while True pattern
The most common reason to use break is a loop where you cannot write a good condition up front. You don't know whether to stop until you have done some work inside the body. In that case, write while True:, which never becomes false by itself, and put the exit test inside the body.
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")The loop asks for a password, counts the attempt, and leaves when the answer is right or the third attempt is used. Without break, you would have to read the input before the loop and again at the end of the body, or add a flag variable. The while True version reads the input in one place.
Sentinel loops
A sentinel is a special value that means "no more data". Reading input until the user enters a sentinel is a classic use of break.
total = 0
while True:
text = input("Number (blank to stop): ")
if text == "":
break
total += int(text)
print("Total:", total)Here the blank line is the sentinel. The test for it comes right after the read, so the sentinel is never added to the total. If you put the break check after total += int(text), the sentinel would be converted first and int("") would raise ValueError. Order matters: test for the exit condition before you use the value.
Retry loops
Retrying something that may fail, with a cap on attempts, uses two break statements. One covers success and the other covers giving up.
def fetch(attempt):
return attempt >= 3 # pretend the third try succeeds
attempt = 0
while True:
attempt += 1
if fetch(attempt):
print("ok on attempt", attempt)
break
if attempt == 5:
print("giving up")
breakThis prints ok on attempt 3. Each exit has its own message, so the code after the loop does not need to work out why the loop ended.
break compared with a condition and a flag
You can often write the same logic without break. Compare the two versions of a retry loop below.
# With a flag
done = False
attempt = 0
while not done and attempt < 5:
attempt += 1
done = attempt >= 3
print(attempt, done)
# With break
attempt = 0
while attempt < 5:
attempt += 1
if attempt >= 3:
break
print(attempt)Both print the same attempt count (3). The flag version keeps all exit rules in the loop header. The break version keeps the header simple and puts the special case where it happens. Use these guidelines to choose:
- If the loop has one natural stopping rule, put it in the condition and skip
break. - If the exit depends on something you only learn midway through the body, use
break. - If you find yourself adding several flags that the rest of the body must check,
breakis usually clearer. - If there are many
breakstatements scattered through a long body, consider moving the loop into a function and usingreturn, or restructuring it.
Where break is allowed
break is valid only inside a loop body. Python reports a SyntaxError for it elsewhere, before the program runs.
| Location of `break` | Result |
|---|---|
| Directly in a `while` or `for` body | Exits that loop |
| Inside an `if` or `try` that is inside a loop | Exits the loop |
| In a loop nested inside another loop | Exits only the innermost loop |
| Outside any loop | `SyntaxError: 'break' outside loop` |
| In a function defined inside a loop | `SyntaxError`, because the function is a separate scope |
The last row catches people who write a helper function inside a loop and try to break out of the outer loop from it. A function cannot break its caller's loop. Have the function return a value and let the loop decide whether to break.
def is_done(value):
return value > 10
n = 0
while True:
n += 3
if is_done(n):
break
print(n)This prints 12. The helper reports the decision, and the loop acts on it.
State after a break
When a loop ends with break, every variable keeps the value it had at that moment. Python does not roll anything back, and the loop does not finish the current pass. You can use this to your advantage, because the loop variable shows exactly where the loop stopped. The same fact explains a common off-by-one mistake.
n = 0
while True:
n += 1
if n == 4:
break
print("processing", n)
print("stopped at", n)The output is processing 1, processing 2, processing 3, then stopped at 4. The value 4 was never processed, because the break came before the print. If you want the value that triggered the exit to be processed too, do the work first and break afterwards.
An update placed after the break check is also skipped on the pass that breaks. In the first example in this chapter, n += 1 was not run when the loop stopped, so n held the value that caused the exit.
break and try/finally
break interacts with try statements in one useful way. If a break runs inside a try block that has a finally clause, Python runs the finally code before it leaves the loop.
n = 0
while True:
try:
n += 1
if n == 2:
break
finally:
print("cleanup", n)
print("after loop, n =", n)The output is:
cleanup 1
cleanup 2
after loop, n = 2The cleanup runs on every pass, including the one that breaks. This is why break is safe in loops that open resources inside a try. In practice you will more often use a with statement, which gives the same guarantee.
break does not skip the loop to run else code
Python lets a loop have an else clause that runs when the condition becomes false normally. A break skips that clause. A later chapter covers the clause in detail. For now, remember that "ended by break" and "ended by the condition" are different outcomes that Python can tell apart.
Common mistakes with break
- Breaking too early. Putting
breakbefore the work you meant to do on the final item, as in theprocessingexample above. - Forgetting the break entirely. A
while Trueloop with no reachablebreak(orreturn, or an exception) never ends. Check everywhile Trueand find the line that ends it. - A
breakguarded by a condition that can never be true. For example,if attempts == 3whenattemptsis incremented by 2 from 0 and so skips over 3. Use>=when a counter might step past the target. - Assuming
breakleaves several loops. It leaves only the innermost one. The chapter on nested loops shows the options. - Using
breakwhenreturnwould be clearer. Inside a function, if leaving the loop means the function is done,returnthe result directly.
The third mistake is easy to reproduce:
count = 0
while True:
count += 2
if count >= 5: # == 5 would never match, because count is 2, 4, 6, ...
break
print(count)This prints 6. With count == 5 in place of count >= 5, the loop would run forever, since count goes from 4 to 6 without ever equaling 5.
Summary of rules
breakends the innermost enclosing loop at once and does not recheck the condition.- Code after the
breakin the body is skipped for that pass. - Variables keep their current values after the loop.
- A
finallyclause around thebreakstill runs. - A loop can end through its condition or through
break. Record which one happened if the code after the loop needs to know. while Truewithbreakfits loops where the exit decision comes mid-body, such as sentinels, retries, and validation.
Exercise
What does this program print, and why? n = 0 while n < 10: n += 3 if n % 2 == 0: break print("n is", n) print("final", n)
Show answer
It prints "n is 3" and then "final 6". On the first pass n becomes 3, which is odd, so the break is skipped and "n is 3" prints. On the second pass n becomes 6, which is even, so break runs before the print. The loop ends without checking n < 10 again, and the last line prints "final 6".
Exercise
Write a loop that repeatedly asks the user for a number with input() and stops when the user types "quit". It should then print the largest number entered, or "No numbers" if none were entered. Use while True and break. Start by deciding where the test for "quit" must go.
Show answer
The test for "quit" must come right after the read and before int() is called, so the sentinel is never converted. largest = None while True: text = input("Number (or quit): ") if text == "quit": break value = int(text) if largest is None or value > largest: largest = value if largest is None: print("No numbers") else: print("Largest:", largest)