Leaving a loop with break and continue¶
~15 min ยท prerequisite: Repeating with for and range
What you will be able to do¶
- Use
breakto leave a loop right away, and continue with the code after the loop. - Use
continueto skip the rest of one round and start the next round. - Use
while Truetogether withbreakfor a loop that stops when a condition is met inside the block.
The idea¶
A break statement is the single word break on its own line inside a loop. When Python runs it, the loop ends immediately. Any lines left in the block are skipped, and Python continues with the first line after the loop.
A continue statement is the word continue on its own line. When Python runs it, the rest of the current round is skipped, and the loop moves on to the next round. In a for loop, that means the next value from the range. In a while loop, Python goes back to check the condition.
Both words affect the loop that directly contains them. Each statement must sit inside a loop.
A common pattern is while True:. The condition is always True, so the loop would never end by itself. A break inside the block is the only way out. This is useful when you cannot know in advance how many rounds you need.
Worked example¶
found = -1
for number in range(1, 20):
if number * number > 50:
found = number
break
print("First square over 50 comes from", found)
Line by line, this is what Python does:
found = -1stores a value that means "not found yet".- The loop tries
numbervalues 1, 2, 3, and so on. - For
numberequal to 1 through 7, theifcondition isFalse, because the squares are 49 or less. - For
numberequal to 8,8 * 8is 64, which is greater than 50. The condition isTrue, sofoundbecomes 8. breakends the loop at once. The values 9 and beyond are never checked.printshows the value offound.
The output is First square over 50 comes from 8.
Now a continue example. It adds only the odd numbers from 1 to 7.
When number is even, continue skips the total += number line. The output is 16, which is 1 + 3 + 5 + 7.
Try it¶
Each block checks its result with assert.
In the second block, n += 1 comes before the continue, so n always changes. That is what lets the loop finish.
Common mistakes¶
-
Putting the counter update after
continue. The following loop never ends:When
nis 1,continuejumps back to the condition beforen += 1runs, sonstays 1 forever. Update the counter before thecontinue, as the try-it block did. -
Using
breakoutside a loop. Writingbreakinside anifthat is not inside a loop gives:Only a
fororwhileloop can containbreak. -
Using
breakwhen you meantcontinue. The following check fails:breakstops the whole loop whennis 3, sototalis only 1 + 2, which is 3. Usecontinueto skip just that round. -
Writing
continueoutside a loop. Writingcontinueat the top level of a program gives:Like
break,continueneeds a loop around it.
Practice¶
- Use a
forloop overrange(1, 50)withbreakto find the first number greater than 20 that is divisible by 7. Assert that the result is 21. - Use a
forloop overrange(10)andcontinueto skip the even numbers. Count the odd numbers and assert that the count is 5. - Use
while Truewith a counter to find the smallestnfor whichn * n * nis greater than 500. Assert thatnis 8. - Use a
forloop overrange(1, 21)to add the numbers 1 through 20, but skip any multiple of 5 withcontinue. Assert that the total is 160. - Stretch: use
while Truewith a counternthat starts at 0. Each round, add 1 ton. Ifnis greater than 10, usebreak. Ifnis a multiple of 3, usecontinue. Otherwise addntototal. Assert thattotalis 37.
Solution
-
python result = -1 for n in range(1, 50): if n > 20 and n % 7 == 0: result = n break assert result == 21 -
python count = 0 for i in range(10): if i % 2 == 0: continue count += 1 assert count == 5 -
python n = 0 while True: n += 1 if n * n * n > 500: break assert n == 8
The value 7 gives 343, which is too small, and 8 gives 512.
-
python total = 0 for n in range(1, 21): if n % 5 == 0: continue total += n assert total == 160 -
python n = 0 total = 0 while True: n += 1 if n > 10: break if n % 3 == 0: continue total += n assert total == 37
The numbers 1 to 10 add up to 55. Removing 3, 6, and 9 leaves 37.
Recap¶
breakends the loop that contains it right away, and the program continues after the loop.continueskips the rest of the current round and starts the next round.- In a
whileloop, update the counter before anycontinue, or the loop may never end.