Concepts / Using break to Exit Loops Early

Using break to Exit Loops Early

The continue statement skips the rest of the current loop iteration and jumps back to the loop start, enabling efficient filtering of uninteresting data.

  • Programming

A Filter Inside the Loop

A loop may examine many input lines even though only some of them matter. The continue statement lets the loop discard an uninteresting line immediately. It stops the current iteration and sends control back to the top of the loop, where the next line can be examined.

Tracing the Skip Path

python

The loop first tests whether the current line starts with From:. The condition uses not, so a line that does not start with From: is identified as uninteresting. For that line, continue runs immediately. The print statement is below continue, so it is skipped for that iteration. A line that does start with From: does not enter the continue path and reaches print instead.

NoYesnext iterationafter processingNext input lineStarts with From:continueSkip remaining codeLoop startprint(line)
When a line fails the search condition, where does control go next, and which statements are skipped?

The Search Pattern

The pattern if not condition: continue is useful because it describes the lines to reject first. If the condition is true, the line is interesting and the code below can process it. If the condition is false, not condition is true, so continue skips the line. This keeps the processing code focused on matching lines rather than nesting it inside another conditional branch.

testYesNoreachesCurrent lineDoes not start withFrom:continueProcessing codeStarts with From:
How does the if not condition: continue pattern filter uninteresting lines while allowing only matching lines to reach the processing code?

A Three-Line Trace

Use a small input to trace the loop rather than trying to reason about every line at once. The sample contains Subject: Meeting, From: alice@example.com, and Date: 2024-01-15. Only the second line begins with From:.

IterationInput lineCondition resultLoop actionReaches print?
1Subject: MeetingDoes not start with From:continue skips the rest of this iterationNo
2From: alice@example.comStarts with From:Continue is not executedYes
3Date: 2024-01-15Does not start with From:continue skips the rest of this iterationNo

Tracing the search loop one input line at a time

Output
From: alice@example.com
continueafter processingcontinueSubject: MeetingskippedNext iterationFrom:alice@example.comprocessedDate: 2024-01-15skipped
For each input line, is it skipped or processed, and what happens before the next iteration?

Compact Conditional Syntax

python

Python allows an if statement and its action to appear on one line. In this contracted form, the condition comes first, followed by a colon and the action. The one-line form functions identically to the indented multi-line form.

Multi-line formContracted form
if not line.startswith("From:"): continueif not line.startswith("From:"): continue
The action appears on the indented next line.The action appears after the colon on the same line.

Continue or Break

StatementEffect on the current iterationEffect on the loop
continueStops executing the remaining statementsJumps back to the loop start for the next iteration
breakStops executing the current iterationExits the loop entirely
  • Treating continue as if it ended the entire loop.

    continue skips only the rest of the current iteration and then returns control to the loop start.

    Fix: Use continue when the loop should move to the next item. Use break when the loop should end immediately.

  • Expecting code after continue to run for the same line.

    Python immediately stops executing the rest of that iteration after continue.

    Fix: Place code below continue only when it should process lines that pass the filter.

  • Forgetting that not reverses the test.

    The pattern tests for the lines to skip, not the lines to process.

    Fix: Read the condition as: if this line is uninteresting, continue.

Try the Trace

EASY

Suppose a search loop uses if not line.startswith("From:"): continue, followed by a processing statement. Predict which of these lines reach the processing statement: Subject: Meeting, From: bob@example.com, and Date: 2024-01-15. Then explain what happens to the other two lines.

Hints
  • The condition identifies lines that do not start with From:.
  • For a line that matches that description, continue skips the remaining statements in the iteration.
  1. Read the current input line.
  2. Ask whether it starts with From:.
  3. If it does not, follow continue and move to the next iteration.
  4. If it does, let the line reach the processing statement.
  5. Repeat the trace for every input line.

Key Takeaways

  1. continue skips the rest of the current loop iteration and starts the next iteration.
  2. The pattern if not condition: continue filters out uninteresting items before the processing code.
  3. Only lines that avoid continue reach statements placed below it.
  4. continue differs from break because break exits the entire loop.
  5. A contracted if places the action on the same line as the condition and behaves like the equivalent multi-line form.

Key Takeaways

  • continue is an early skip for one loop iteration, not a command to end the whole loop.
  • if not condition: continue makes a search loop reject uninteresting lines before processing matching lines.
  • Tracing each input line reveals exactly which statements are skipped and which are reached.
  • The contracted if form keeps a condition and its continue action on one line.
  • break exits the loop entirely, so it has a different purpose from continue.