Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 149 ยท Control Flow

break, continue and Loop else

Control Python loops precisely. Exit early with break, skip iterations with continue, use the for/while else clause for searches, and fill empty blocks with pass.

Most loops run from start to finish: every item of a for loop gets processed, or a while loop runs until its condition turns false. Real programs often need finer control. You might want to stop searching as soon as you've found what you need, or skip records that are blank or invalid without wrapping the whole body in an if.

Python gives you two statements for this: break leaves a loop immediately, and continue jumps to the next iteration. Loops also have an unusual feature that many developers never learn: an else clause that runs only when the loop finishes without a break. This lesson covers all three, plus pass, the statement that does nothing on purpose.

break: leave the loop now

When Python reaches break, it exits the innermost loop at once. Any remaining items are ignored, and execution continues with the first line after the loop.

Python Stop at the first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop checks 120, 45 and 310, then stops. The orders 80, 990 and 15 are never looked at. Stopping early like this saves time when the data is large, and it also makes your intent clear: "I only need the first one".

break is equally useful in while loops, especially the while True pattern, where it's the only way out:

Python break in a while True loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fourth input line is never read, because the loop ended at "quit".

continue: skip to the next iteration

continue abandons the current iteration and goes back to the top of the loop. In a for loop that means moving to the next item; in a while loop it means re-checking the condition.

Python Skipping bad records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This style is sometimes called a guard clause: handle the cases you want to reject at the top of the body, then write the main logic without extra indentation. Compare it with the nested alternative:

Python
for raw in readings:
    raw = raw.strip()
    if raw:
        if raw != "error":
            valid.append(float(raw))

Both work, but the continue version stays flat as more checks are added.

Warning: In a while loop, make sure the progress step happens before any continue. If i += 1 sits at the bottom of the body and a continue skips it, the loop can run forever.

break and continue in nested loops

Both statements affect only the innermost loop that contains them. A break inside an inner loop ends that inner loop, and the outer loop carries on.

Python break only exits one loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python has no "break out of two loops" statement. When you need to stop everything from deep inside, the cleanest options are:

  • Put the nested loops in a function and use return, which exits the whole function.
  • Use a flag variable that the outer loop checks.
  • Use the loop else trick shown below.

The else clause on loops

Both for and while loops may have an else block. It runs once, after the loop ends normally, meaning the loop wasn't stopped by break.

  • A for loop ends normally when it runs out of items.
  • A while loop ends normally when its condition becomes false.
  • If break runs, the else block is skipped.

That sounds odd at first, but it fits searching perfectly: "look through the items; if you found it, break; otherwise (if nothing triggered the break), report that it wasn't found."

Python Search with for/else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without else, you'd need a flag:

Python
found = False
for user in users:
    if user["name"] == name:
        found = True
        break
if not found:
    print(f"No user called {name}")

The else version removes the extra variable. A neat way to remember it is to read else as "no break".

Here's a classic use: testing whether a number is prime by trying every possible divisor.

Python Prime numbers with for/else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the indentation: the else lines up with the inner for, not with the if. That's what makes it a loop else rather than an if/else. For n = 2 and n = 3, the inner range is empty, the loop body never runs, and the else executes, correctly reporting them as prime.

Note: Loop else is legitimate, idiomatic Python, but some readers find it surprising. When you use it, keep the loop short so the break and the else are visible together, or add a brief comment like # no break.

The same works with while:

Python
attempts = 0
while attempts < 3:
    attempts += 1
    if try_to_connect():
        print("Connected")
        break
else:
    print("Gave up after 3 attempts")

pass: a statement that does nothing

Python requires every block (a loop body, an if branch, a function body) to contain at least one statement. Sometimes you genuinely have nothing to do there yet. pass fills the gap:

Python Using pass as a placeholder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Don't confuse the three statements:

Statement What happens
break Leaves the loop entirely (and skips any loop else)
continue Ends this iteration; the loop goes on with the next one
pass Nothing at all; execution continues with the next line

Remove pass from an otherwise empty block and Python raises IndentationError: expected an indented block. A docstring or the literal ... (Ellipsis) also counts as a statement, so you'll sometimes see ... used as a placeholder instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? for n in [1, 2, 3, 4]: โ†’ if n == 3: break โ†’ print(n)

    When n is 3, break exits before the print, so only 1 and 2 are printed.
  2. 2. What does this print? for n in [1, 2, 3, 4]: โ†’ if n == 3: continue โ†’ print(n)

    continue skips only the iteration where n is 3; the loop then goes on with 4.
  3. 3. When does the else block of a for loop run?

    A loop's else runs after a normal finish (including an empty iterable) and is skipped if break ran.
  4. 4. A break inside an inner loop of two nested loopsโ€ฆ

    break affects only the innermost enclosing loop. Use return inside a function to leave both.
  5. 5. What does pass do?

    pass is a no-op. It keeps the syntax valid in blocks you haven't written yet or deliberately leave empty.

Summary

  • break exits the innermost loop immediately; the rest of the items are never processed.
  • continue skips the rest of the current iteration and moves on to the next one.
  • Use continue as a guard clause to reject bad data early and keep the main logic unindented.
  • In while loops, update the loop variable before any continue to avoid infinite loops.
  • A loop's else block runs only if the loop finished without break: read it as "no break". It's ideal for searches.
  • pass does nothing and fills blocks that must exist but have no code yet.

Next: range(), where you'll generate number sequences for counting, stepping and counting down.