Sub topic 10
Controlling a Loop with break and continue
This chapter assumes you can write a basic for loop over a list or a range(), and that you are comfortable with if statements and boolean expressions. It covers the two statements that change a loop's normal flow, how they behave in edge cases, and the mistakes that come up most often.
The default flow and the two exceptions
A for loop normally runs its body once for every item, then stops when the iterable is exhausted. Two statements change that:
breakends the loop immediately. Execution continues with the first statement after the loop.continueends only the current iteration. The loop moves on to the next item.
Both are only legal inside a loop body. Using either one outside a loop is a SyntaxError.
Stopping early with break
Use break when the loop has found what it was looking for, so that further iterations would be wasted work or would give a wrong answer.
names = ["Ada", "Grace", "Linus", "Guido"]
target = "Linus"
for index, name in enumerate(names):
if name == target:
print("found", target, "at index", index)
break
print("search finished")This prints found Linus at index 2, then search finished. The loop never looks at "Guido". For a list of a million names where the match is near the front, this saves most of the work.
A common shape is a search loop that remembers a result:
numbers = [3, 8, 12, 5, 20]
first_big = None
for n in numbers:
if n > 10:
first_big = n
break
print(first_big) # 12If no number exceeds 10, first_big stays None. Initialize the result before the loop so that both outcomes, found and not found, leave it defined. When you only need the first match, the built-in next() with a generator expression does the same job in one line:
numbers = [3, 8, 12, 5, 20]
first_big = next((n for n in numbers if n > 10), None)
print(first_big) # 12The second argument to next() is the default returned when nothing matches.
Skipping an item with continue
Use continue when some items should be ignored but the loop should keep going. It works well as a guard at the top of the body, because it avoids wrapping the real work in a deeper if block.
lines = ["name=Ada", "", "# a comment", "role=admin"]
for line in lines:
if not line or line.startswith("#"):
continue
key, value = line.split("=")
print(key, "->", value)Output:
name -> Ada
role -> adminWithout continue, the same logic needs the parsing code nested under if line and not line.startswith("#"):. With several skip conditions, the nesting grows. Several guard clauses that each continue keep the main logic at one indentation level.
Use this style when the skip conditions are simple and the main work is longer. When there is a single short condition, a plain if around the work is often just as readable.
What happens to the loop variable
After break, the loop variable keeps the value it had when the loop stopped. This is the same rule you saw for loop variables in general, and it lets you use the variable after the loop:
for i in range(10):
if i * i > 20:
break
print(i) # 5, because 5 * 5 = 25 is the first square above 20If the loop finishes without break, i is the last value produced, which is 9 here. So i alone cannot tell you whether the loop stopped early. If you need to know, set a flag or result variable before break, as in the first_big example above.
With continue, the variable simply takes the next value on the next iteration. Nothing else is reset.
break and continue in nested loops
Both statements affect only the innermost loop that contains them. This catches many people the first time they search a grid:
grid = [[1, 2], [3, 4], [5, 6]]
for row in grid:
for value in row:
if value == 3:
break # leaves only the inner loop
print("finished row", row)This prints finished row [1, 2], finished row [3, 4] and finished row [5, 6]. The break stops scanning row [3, 4], but the outer loop carries on with the next row.
Python has no labeled break. To leave several loops at once, you have three practical options:
- Move the loops into a function and use
return. - Set a flag in the inner loop, then test it and
breakin the outer loop. - Restructure the search so one loop is enough, for example with a generator.
The function approach is usually the cleanest:
def find_value(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return r, c
return None
print(find_value([[1, 2], [3, 4]], 3)) # (1, 0)
print(find_value([[1, 2], [3, 4]], 9)) # NoneNested loops are covered in their own chapter. The point to remember here is that a break has a narrow reach.
Choosing between break, continue and return
| Statement | Effect | Typical use |
|---|---|---|
| `break` | Leaves the innermost loop, then runs the code after it | Stop once a result is found |
| `continue` | Skips to the next iteration of the innermost loop | Ignore items that do not qualify |
| `return` | Leaves the loop and the whole function | Exit several nested loops, or deliver a result immediately |
Common mistakes
Putting code after continue
Statements after continue in the same block never run. Linters report this as unreachable code, but only when the continue is unconditional. Check that the work you want on every item comes before the continue, or that it does not depend on the skipped path.
total = 0
count = 0
for n in [4, -1, 6, -3, 8]:
count += 1 # counts every item, including skipped ones
if n < 0:
continue
total += n
print(total, count) # 18 5If count += 1 were placed after the if, it would count only the non-negative items, and the result would be 18 3. Which one is right depends on what you mean to count, so decide on purpose.
Using continue in a while loop without advancing
A for loop moves to the next item by itself, so continue is safe. A while loop does not. If the counter update comes after the continue, the skipped path never updates it, and the loop never ends:
i = 0
while i < 5:
if i == 2:
i += 1 # without this line the loop would repeat i == 2 forever
continue
print(i)
i += 1This prints 0, 1, 3 and 4. When you convert a while loop to for with range(), this problem disappears, which is one reason for is preferred when the number of iterations is known.
Reaching for break when a condition would do
If you find yourself writing for ...: if x: break to build a filtered list, a comprehension or any() is clearer. A check like "does any item match?" reads best as a single expression:
numbers = [3, 8, 12, 5, 20]
print(any(n > 10 for n in numbers)) # Trueany() also stops at the first true value, so it short-circuits just as break does.
Skipping cleanup
break and continue do not skip finally blocks. If the loop body is inside a try ... finally, the finally code runs before control leaves the iteration. This matters if you open a resource inside the loop. Use a with statement and the resource closes properly however the iteration ends.
A related feature: the loop else clause
A loop can have an else block that runs only when the loop was not ended by break. It is a later chapter's topic, but it explains why break is more than a convenience: it changes which code runs afterward.
Summary of the working model
breakexits the innermost loop at once and keeps the loop variable's current value.continueabandons the rest of the current iteration and fetches the next item.- Neither crosses a loop boundary. To leave nested loops, use
returnfrom a function or a flag. - Initialize any result variable before the loop so it is defined whether or not
breakruns. - In a
whileloop, make surecontinuecannot bypass the statement that advances the loop.
Exercise
The code below is meant to print the first negative number in the list and then stop. It prints -2 and then also prints 7 and -5 on later lines. What is wrong, and how do you fix it? data = [4, -2, 7, -5] for n in data: if n < 0: print(n) continue
Show answer
The loop uses continue, which only skips to the next iteration, so the loop keeps going and prints every negative number. Replace continue with break so the loop ends after the first negative value. The output is then just -2. If you also want a value to use after the loop, assign it to a variable that was set to None before the loop, then break.
Exercise
What does this code print, and why? for i in range(1, 4): for j in range(1, 4): if j == 2: break print(i, j)
Show answer
It prints "1 1", "2 1" and "3 1", each on its own line. For every value of i, the inner loop prints j = 1, then reaches j = 2 and hits break. The break leaves only the inner loop, so the outer loop continues with the next i. The values j = 2 and j = 3 are never printed.