Module 3 · Control Flow & Logic ⏱ 15 min

Loop Control: break & continue

By the end of this lesson you will be able to:
  • Use break to exit a loop early when a condition is met
  • Use continue to skip the rest of the current iteration
  • Place guard checks above the real work so nothing slips through
  • Explain why break and continue affect only the innermost loop

Not every loop should run to completion. Sometimes you are searching for one answer and want to stop the moment you find it; sometimes a few items are invalid and you want to skip them but keep going. Two keywords give you that control:

  • break ends the loop immediately. Python jumps to the first line after the loop, ignoring any items that were left.
  • continue ends only the current iteration. Python skips the rest of the body for this one item and moves straight to the next.

Use break for search — find a match and stop, because the remaining items no longer matter. Use continue for filtering — discard items that do not apply, then process the ones that do. Both keywords work in for loops and while loops alike.

flowchart LR
  S["start loop"] --> C{"condition met?"}
  C -- "continue" --> N["next iteration"]
  C -- "break" --> E["exit loop"]
  C -- "neither" --> B["run body"]
  B --> N
  style C fill:#3776ab,color:#fff
break exits the loop entirely; continue skips to the next iteration.

Here is a loop that does both at once. It skips negative values with continue and stops early with break the moment it sees a value above one hundred:

continue skips negatives; break stops at the first value over 100.
values = [10, -5, 20, 150, 30]
for v in values:
    if v < 0:
        continue
    if v > 100:
        print('stopping at', v)
        break
    print('ok', v)

Where you put the check changes everything

break and continue take effect the instant Python reaches them, so their position in the body decides what runs. Put a continue before the work and the current item is skipped cleanly; put it after the work and it does nothing useful, because there is nothing left to skip. The same applies to break — a check placed too early can halt the loop before any real work happens.

This is why almost every loop with these keywords follows the same shape: run the guard checks first (skip with continue, stop with break), then do the real work underneath. Checks on top, work below. Following that order keeps the flow readable and avoids the classic bug where a value slips through because a skip ran one line too late.

break exits only one loop

When loops sit one inside another, break and continue always act on the innermost loop they live in — they never leap outward. A break in the inner loop ends just that inner loop; the outer loop carries on to its next iteration as if nothing happened. If you genuinely need to stop every loop at once, the cleanest tool is usually a small function: a return exits all of them at once, with no flags to juggle.

Keeping this scope rule in mind saves you from the common surprise where a break felt like it 'did nothing' — it did work, just on the loop you forgot you were inside.

flowchart TD
  O["outer loop"] --> I["inner loop"]
  I --> B{"break inside?"}
  B -- "yes" --> X["exits inner loop only"]
  X --> O
  B -- "no" --> W["run inner body"]
  W --> I
  style B fill:#3776ab,color:#fff
  style X fill:#b45309,color:#fff
break leaves only the loop it lives in; the outer loop keeps running.
break leaves only the inner loop; the outer loop continues.
# break ends the inner loop, not the outer one.
for letter in "ab":
    for n in range(3):
        if n == 1:
            break
        print(letter, n)

Knowing whether you found anything

A search loop often needs to do one thing if it found a match and another if it ran out of items without one. Python offers a tidy tool for this: attach an else directly to the loop. The else block runs only when the loop finished normally — that is, without hitting a break. If a break fired, the else is skipped entirely:

for n in numbers:
    if n == target:
        print("found")
        break
else:
    print("not found")

Read that else as 'the loop completed without breaking.' It is optional, but it removes the need to track a separate found = False flag by hand.

Exercise

Write first_even(numbers) that returns the first even number in the list, using break to stop once it finds one. If there is no even number, return None.

def first_even(numbers):
    found = None
    for n in numbers:
        # when n is even, store it and break
        pass
    return found
Exercise

Write skip_and_sum(numbers) that adds up all numbers in the list, skipping any negatives using continue.

def skip_and_sum(numbers):
    total = 0
    for n in numbers:
        # skip negatives, then add to total
        pass
    return total
Exercise

What does this print? Watch how continue and break interact.

for i in range(5):
    if i == 2:
        continue
    if i == 4:
        break
    print(i)
Exercise

This should add up every number except 13, but it stops the whole loop the first time it sees 13. The wrong keyword was used — it should skip just that one item, not halt everything.

def sum_skipping_unlucky(numbers):
    total = 0
    for n in numbers:
        if n == 13:
            break        # bug: should skip only this item
        total += n
    return total
Exercise

Write take_until(items, sentinel) that returns a new list of the items from the start of items, stopping before the first item equal to sentinel. If the sentinel never appears, return all the items.

def take_until(items, sentinel):
    result = []
    for x in items:
        # stop when x equals sentinel; otherwise collect it
        pass
    return result

while loops: break as the exit door

A for loop runs a known number of times, but some loops have no fixed count — they run until a condition is met somewhere in the body. The idiomatic shape is while True: with a break that fires the moment you are done. This 'loop-and-a-half' form puts the exit check right next to the work that decides it, instead of repeating the condition at the top and again inside:

while True:
    item = get_next()
    if item is None:
        break
    process(item)

Read it as 'keep going, and here is exactly when to stop.' Because this pattern reads from top to bottom with no tangled exits, experienced programmers reach for it whenever the stopping condition is not a simple counter.

continue versus a plain if

Beginners sometimes reach for continue when an ordinary if would do the same job with less ceremony. If the body after the check is short, wrapping it in an if and dropping the continue is usually clearer, because there is one less concept to track. continue earns its place when skipping lets you avoid nesting the real work inside several layers of if.

As a rule of thumb, use continue to handle a few early 'this item does not apply' cases at the top of a long body, then write the main logic at the outer indentation. When the skip is the only thing happening, a plain conditional reads better. Pick the form that keeps the happy path at the left margin.

Recap

  • break ends the loop now; continue ends only this iteration and moves to the next.
  • Reach for break in searches and continue in filters.
  • Put guard checks (skip or stop) above the real work so nothing slips through.
  • In nested loops, break and continue affect only the innermost loop.
  • A loop's else runs only when no break fired — handy for 'not found' cases.

Next you'll combine loops with lists to transform and filter whole collections at once.

Checkpoint quiz

What does break do inside a loop?

In for n in nums: if n < 0: continue, what happens when n is negative?

A break inside the inner loop of two nested loops does what?

Go deeper — technical resources