Sub topic 10
Controlling a loop with break and continue
This chapter assumes you can write a basic for loop over a list or range(), use if statements, and run a Python 3 script. By default a for loop visits every item. break and continue let you change that from inside the loop body.
What each statement does
breakends the whole loop immediately. Execution resumes at the first statement after the loop.continueends only the current iteration. The loop moves on to the next item.
Using break to stop early
Use break when you have found what you need and further work is wasted. This loop searches for the first negative number.
readings = [12, 7, 3, -4, 9, -1]
first_negative = None
for value in readings:
if value < 0:
first_negative = value
break
print(first_negative) # -4The loop stops at -4. It never looks at 9 or -1.
Using continue to skip an item
Use continue when some items should be ignored but the loop must keep going. This loop adds up only the positive numbers.
readings = [12, 7, 3, -4, 9, -1]
total = 0
for value in readings:
if value <= 0:
continue
total += value
print(total) # 31When value is -4, continue jumps straight to the next item, so total += value does not run for it.
A common use of continue is a guard at the top of the body. It handles the unwanted case first and keeps the main logic at one indentation level, instead of wrapping it in a deeper if.
Combining both
You can use both in one loop. This one reads commands until it sees "quit" and ignores blank lines.
commands = ["start", "", "status", " ", "quit", "start"]
for command in commands:
command = command.strip()
if command == "":
continue
if command == "quit":
break
print("running:", command)The output is running: start and then running: status. The blank entries are skipped, and the loop ends at "quit" without touching the final "start".
Behavior to remember
breakandcontinueaffect only the innermost loop that contains them. In nested loops, an innerbreakdoes not stop the outer loop.- Code after
continueorbreakin the same iteration never runs, so place any needed cleanup or counting before them. - Both statements are only valid inside a loop. Using them elsewhere is a
SyntaxError.
Common mistakes
- Putting
continuebefore a statement that must always run, such as a counter update, so that statement gets skipped. - Expecting
breakinside an inner loop to exit both loops. - Using
breakwherecontinuewas meant, which ends the loop on the first unwanted item instead of skipping it.
Exercise
What does this code print? for n in range(1, 8): if n % 2 == 0: continue if n > 5: break print(n)
Show answer
It prints 1, 3 and 5, each on its own line. Even numbers are skipped by continue. When n reaches 7 (odd), the check n > 5 is true, so break ends the loop before print runs.