break Statement Programs
break is for the moment there is nothing left worth doing. You have found what you were looking for, or you have proved the answer is no — carrying on would only waste rounds. The loop stops immediately: this round is abandoned halfway and so is every round that was still to come.
1Program 1 — search a list and stop when you find it
A list holds six roll numbers. Ask which one to look for and stop searching the moment it turns up.
- the roll number to find,
wanted
- look at each roll number in turn
- stop as soon as one matches
- every roll number looked at, and whether it was found
# search a list and stop the moment the value is found
rolls = [11, 24, 37, 42, 58, 63]
wanted = int(input('Which roll number? '))
for r in rolls:
print('Looking at', r)
if r == wanted:
print('Found it')
breakWhich roll number? 37 Looking at 11 Looking at 24 Looking at 37 Found it
Three roll numbers looked at, not six. The list did not get shorter — the loop simply stopped, and 42, 58 and 63 were never handed out. That saving is the entire point of break, and on a list of six it is invisible; on a list of sixty thousand it is the difference between a program that answers and one that hangs.
Which roll number? 99 Looking at 11 Looking at 24 Looking at 37 Looking at 42 Looking at 58 Looking at 63
break was never reached, so the loop ran out of values and ended normally — and there is no line anywhere that prints “not found”. This is the hole every search program has to close, and Python has a neat way to close it.2Program 2 — the same search, with else
Report both outcomes: say whether the roll number is on the list or not.
# the same search, with an else that runs only when nothing was found
rolls = [11, 24, 37, 42, 58, 63]
wanted = int(input('Which roll number? '))
for r in rolls:
if r == wanted:
print('Roll number', wanted, 'is on the list')
break
else:
print('Roll number', wanted, 'is not on the list')Which roll number? 42 Roll number 42 is on the list
Which roll number? 99 Roll number 99 is not on the list
else:Lined up with for, not with if — that indentation is the only thing that says which of the two it belongs to. A loop's else runs when the loop finished normally, which here means the break was never reached.
breakTwo jobs at once: it stops the search, and by stopping it, it cancels the else. Take the break out and the program would report both messages.
else means “we got to the end without breaking”. Not “otherwise”, the way an if's else does. It is the tidy way to write not found — the alternative is a flag variable set to False before the loop, set to True at the match, and tested afterwards.3Program 3 — is the number prime?
A prime number has no divisor except 1 and itself. Ask for a number and say whether it is prime.
# is the number prime? stop at the first divisor found
n = int(input('Enter a number: '))
if n < 2:
print(n, 'is not prime')
else:
for i in range(2, n):
if n % i == 0:
print(n, 'is not prime. It divides by', i)
break
else:
print(n, 'is prime')Enter a number: 29 29 is prime
Enter a number: 39 39 is not prime. It divides by 3
Enter a number: 1 1 is not prime
One divisor is enough to settle it. As soon as 39 % 3 comes out 0 the answer is decided, and testing 4, 5, 6 … 38 would change nothing. So the program breaks — and because it broke, the for's else does not run.
if n < 2: guard is not decoration. Without it, ask about 1 and range(2, 1) is empty — so the loop body never runs, the loop ends normally, the else fires, and the program announces that 1 is prime. It is not. We ran it. Many textbook versions of this program have exactly that bug.elses, and only the indentation tells them apart. The first belongs to if n < 2: and the second, four spaces further in, belongs to the for. Read the column they start in, not the order they appear in.4Program 4 — stop at the first impossible reading
A list holds temperature readings. A negative value means the sensor broke, and everything after it is untrustworthy. Print the readings up to that point and stop.
# stop reading the readings at the first impossible one
readings = [23, 27, 25, -1, 29, 31]
for r in readings:
if r < 0:
print('Bad reading found, stopping here')
break
print('Temperature:', r)
print('Report ended')Temperature: 23 Temperature: 27 Temperature: 25 Bad reading found, stopping here Report ended
Notice what did not happen: -1 was never printed as a temperature. break leaves the round immediately, so the print() below it in the same body is skipped along with everything else. And Report ended still appears, because a broken loop hands control to the line after the loop, not out of the program.
break ends the loop, not the program. Anything written after the loop, at the margin, runs exactly as it would have done. Students often expect the program to stop dead; it does not.5Program 5 — a menu that runs until the user quits
Show a menu over and over until the user chooses to quit.
# a menu that keeps coming back until the user chooses to quit
while True:
print('1. Say hello')
print('2. Quit')
choice = int(input('Your choice: '))
if choice == 2:
print('Goodbye')
break
if choice == 1:
print('Hello!')
else:
print('That is not on the menu')1. Say hello 2. Quit Your choice: 1 Hello! 1. Say hello 2. Quit Your choice: 3 That is not on the menu 1. Say hello 2. Quit Your choice: 2 Goodbye
while True: is a condition that can never be false, so on its own it is an endless loop — the break is the only way out, and that is the shape being taught here. It reads honestly: keep going until something says stop, and the thing that says stop is in the middle of the body where the decision is actually made.
while True whose break you have mistyped will lock the page, because the Python here shares the tab — and the whole risk of this shape is that the way out is one line you can get wrong.6Program 6 — break inside a nested loop
Show what break does when there are two loops: which one does it leave?
# break leaves the inner loop only — the outer one carries on
for row in range(1, 4):
print('Row', row)
for col in range(1, 6):
if col == 3:
break
print(' column', col)
print('Done')Row 1 column 1 column 2 Row 2 column 1 column 2 Row 3 column 1 column 2 Done
break leaves one loop — the nearest one it is inside. Here it ends the column loop, and the row loop carries straight on to its next round, where the column loop starts again from 1. There is no keyword in Python for breaking out of both; you would need a flag variable checked by the outer loop as well.7Recap
The rest of this round is skipped and so is every round still to come. The line after the loop runs next.
Statements after the loop still run. break is not exit().
for…else is the clean 'not found'. It runs only when the loop ran out of values without ever breaking.
The nearest enclosing loop. The outer one continues with its next round as though nothing happened.
- 1
Search a list of names for one the user types, and report whether it is there.
Hint · Program 2 with strings. Compare with
==, and remember capitals matter. - 2
Find the first number in a list that divides by 7, and stop.
Hint · The test is
n % 7 == 0; afor…elsecovers the case where there is none. - 3
Keep asking for a number until the user enters one between 1 and 100.
Hint ·
while True, andbreakwhen the number is in range. This shape is how real programs check input. - 4
Add up numbers the user types, stopping at the first negative one without adding it.
Hint · Test and
breakbefore the line that adds — the order of those two lines is the whole question. - 5
Print the smallest divisor of a number greater than 1 (for 39, that is 3).
Hint · The prime program with the message changed. The first divisor found is the smallest, because the loop counts upwards.
A loop prints each value, and breaks when it finds 37 in [11, 24, 37, 42, 58, 63]. How many values are printed?
When does a for loop's else block run?
In a nested loop, a break inside the inner loop is reached. What happens next?