Most loops run until their condition or iterable is exhausted. Two statements let you change that behaviour from inside the loop.
break#
break exits the nearest enclosing loop immediately. No further iterations run.
numbers = [4, 8, 15, 16, 23, 42]
for number in numbers:
if number > 10:
print("First value above 10:", number)
breakFirst value above 10: 15
Values after 15 are never visited. This is useful for searching:
names = ["Ada", "Grace", "Linus"]
target = "Grace"
for name in names:
if name == target:
print("Found", target)
break
else:
print("Not found")continue#
continue skips the rest of the current iteration and moves to the next one.
for number in range(1, 8):
if number % 2 == 0:
continue
print(number)1 3 5 7
Only odd numbers reach the print(). The loop itself continues normally.
break out of nested loops#
break affects only the innermost loop:
for row in range(3):
for column in range(3):
if column == 1:
break
print(row, column)For each row, only column 0 is printed because the inner loop stops at column 1. If you need to leave both loops, set a flag and check it in the outer loop, or move the search into a function and return.
def find_pair(rows, columns, target):
for row in range(rows):
for column in range(columns):
if row * column == target:
return row, column
return None
print(find_pair(5, 5, 6))Loop else#
A for or while loop may have an else block. It runs only when the loop finishes without hitting break.
numbers = [3, 7, 11]
for number in numbers:
if number % 2 == 0:
print("Found an even number")
break
else:
print("No even numbers")No even numbers
If the list contained an even number, break would skip the else. The else is not a fallback for an empty loop; an empty loop still runs it.
Practice#
Write a program that reads numbers until it encounters a negative value, then prints the sum of the non-negative numbers. Use break for the stopping condition and continue to skip zeros if you like. Predict what happens if the input contains only non-negative numbers and the lines run out.
