Module 3 · Beginner · Conditions and loops

Python break, continue and pass, with examples

Python break, continue and pass with examples: stop a loop early, skip one item, leave a placeholder, exit nested loops, and the mistakes beginners make.

By theprogrammers team · · 10 min read

You're checking a list of 1,000 UPI payments for one suspicious amount. Once you find it, there's no reason to look at the other 900. And if a payment failed, you want to skip it and move to the next one. Python's break, continue and pass statements handle exactly these jobs inside a loop.

break stops the loop completely. continue skips the rest of the current pass and goes to the next item. pass does nothing at all, which is surprisingly useful when Python needs a line of code but you don't have one yet.

What you need first: Python for and while loops and Python if, elif and else.

Key terms

  • Loop body: the indented lines that run on each pass of a loop.
  • Iteration: one pass through the loop body.
  • break: a statement that ends the loop at once. Python jumps to the first line after the loop.
  • continue: a statement that ends the current iteration only. The loop carries on with the next item.
  • pass: a statement that does nothing. It fills a spot where Python needs at least one line.
  • Placeholder: code that stands in for something you'll write later.

How break works in Python

break ends the loop the moment Python reaches it. Any items still left are never looked at.

payments = [250, 1200, 99, 5000, 430]

for amount in payments:
    if amount > 2000:
        print(f"Large payment found: ₹{amount}")
        break
    print(f"Checked ₹{amount}")

print("Done")
Checked ₹250
Checked ₹1200
Checked ₹99
Large payment found: ₹5000
Done

The payment of ₹430 is never checked. Python left the loop at break and went straight to print("Done").

break in a while loop

break is most common with while True, a loop that would run for ever on its own. You stop it from inside once something happens:

balance = 500
day = 0

while True:
    day += 1
    balance -= 120          # spend ₹120 a day
    if balance < 0:
        break

print(f"The money runs out on day {day}")
The money runs out on day 5

After four days the balance is ₹20. On day 5 it drops to −₹100, so the loop stops. You could write this as while balance >= 0, but while True with break is often easier to read when the stopping check sits in the middle of the work.

How continue works in Python

continue skips the rest of the loop body for this item only. The loop then moves on to the next item as normal.

Say a class register uses −1 for a student who was absent. You want the average of the students who sat the test:

marks = [78, -1, 92, 65, -1, 89]    # -1 means absent

total = 0
count = 0
for mark in marks:
    if mark == -1:
        continue
    total += mark
    count += 1

print(f"Average of {count} students: {total / count:.1f}")
Average of 4 students: 81.0

For each −1, continue jumps back to the top of the loop, so that mark is never added.

The continue trap in while loops

In a while loop, make sure the line that moves the loop forward runs before continue. Here the counter goes up first, so the loop always moves on:

n = 0
while n < 10:
    n += 1
    if n % 3 == 0:
        continue        # skip multiples of 3
    print(n, end=" ")
1 2 4 5 7 8 10

If you put n += 1 at the bottom of the loop instead, continue would skip it as soon as n is 3. n would stay at 3 for ever, and the program would never finish. If that happens, press Ctrl+C to stop it.

break or continue?

You want toUseExample
Stop as soon as you've found what you needbreakFirst failed payment, a correct password
Skip a bad item but keep goingcontinueBlank rows, absent students, invalid entries
Run code only if the loop didn't stop earlyfor ... else"Not found" messages

continue can often be replaced with an if around the rest of the body. Use continue when it saves you from deep indentation, especially when you check several bad cases at the top of the loop.

break only exits one loop

This trips up almost everyone the first time. In nested loops, break leaves only the innermost loop. The outer loop keeps going:

for row in range(1, 4):
    for seat in range(1, 4):
        if seat == 2:
            break
        print(row, seat)
1 1
2 1
3 1

The inner loop stops at seat 2 every time, but the outer loop still runs for rows 1, 2 and 3.

To stop both loops, the cleanest way is to put them in a function and use return, which leaves the whole function at once:

def find_seat(hall, name):
    for row_number, row in enumerate(hall, start=1):
        for seat_number, person in enumerate(row, start=1):
            if person == name:
                return row_number, seat_number
    return None

hall = [["Ahana", "Rohan"], ["Meera", "Kabir"], ["Dev", "Sara"]]
print(find_seat(hall, "Kabir"))
print(find_seat(hall, "Tanvi"))
(2, 2)
None

The other way is a flag: a True/False variable you set before breaking out of the inner loop, then check in the outer loop. It works, but the function version is shorter and harder to get wrong.

break with for ... else

A loop's else block runs only if the loop finished without a break. It's the neat way to say "I looked everywhere and didn't find it":

roll_numbers = [101, 104, 108, 115]
wanted = 110

for roll in roll_numbers:
    if roll == wanted:
        print("Found")
        break
else:
    print(f"Roll number {wanted} is not on the list")
Roll number 110 is not on the list

The name confuses people, because else here has nothing to do with if. Read it as "no break".

What pass does in Python

Python uses indentation to know what belongs inside a function, loop or if. Each of these needs at least one indented line. If you leave the body empty, you get an error:

def send_otp(phone):

print("Program started")
IndentationError: expected an indented block after function definition on line 1

pass fixes this. It's a line of code that does nothing:

def send_otp(phone):
    pass    # TODO: write this once the SMS service is ready

class Student:
    pass

print("Program started")
Program started

You'll use pass for:

  • Functions you plan to write later, so the rest of the program still runs.
  • Empty classes, often for custom exceptions (see Python exceptions).
  • An except block where you deliberately ignore an error. Be careful with this one: silently ignoring errors hides bugs.

You may also see ... (three dots, called Ellipsis) used the same way: def send_otp(phone): .... Both work. pass is the more common choice in beginner code.

pass is not the same as continue

pass does nothing and lets the code below it run. continue jumps to the next iteration and skips the code below it.

for n in range(1, 5):
    if n == 2:
        pass
    print(n, end=" ")
print()

for n in range(1, 5):
    if n == 2:
        continue
    print(n, end=" ")
1 2 3 4
1 3 4

With pass, 2 is still printed. With continue, it's skipped.

Common mistakes

  • Using break when you meant continue. If your loop stops after the first bad item, check which one you wrote.
  • Expecting break to stop all loops. It only leaves the innermost one. Use a function and return.
  • Putting the counter after continue in a while loop, which causes an infinite loop.
  • Leaving pass in finished code. A function that only contains pass returns None without doing its job, and nothing warns you. Search your code for pass and TODO before you call it done.

Where you'll use these

  • Data cleaning: continue past blank or broken rows when reading a file.
  • Searching: break once a match is found, so a search over 1 lakh records stops early.
  • Menus and games: while True with break when the user chooses "Exit".
  • Machine learning: training loops often break early when the model stops improving, a trick called early stopping.

Practice

  1. Print the numbers from 1 to 50, but stop as soon as you reach the first number divisible by both 4 and 6.
Show the answer
for n in range(1, 51):
    print(n, end=" ")
    if n % 4 == 0 and n % 6 == 0:
        break
1 2 3 4 5 6 7 8 9 10 11 12

12 is the first number divisible by both 4 and 6. The print comes before the check, so 12 is printed before the loop stops.

  1. Print every character of "data science" except the vowels and the space, using continue.
Show the answer
for ch in "data science":
    if ch in "aeiou ":
        continue
    print(ch, end="")
dtscnc
  1. What does this print? Work it out by hand first.
for i in range(3):
    for j in range(3):
        if j == i:
            break
        print(i, j)
Show the answer
1 0
2 0
2 1

When i is 0, the inner loop breaks straight away at j = 0, so nothing prints. When i is 1, it prints 1 0 and breaks at j = 1. When i is 2, it prints 2 0 and 2 1, then breaks at j = 2.

  1. Given scores = [45, 82, 37, 91, 60], use a for ... else loop to print the first score below 40, or "Everyone passed" if there isn't one.
Show the answer
scores = [45, 82, 37, 91, 60]
for score in scores:
    if score < 40:
        print(f"First fail: {score}")
        break
else:
    print("Everyone passed")
First fail: 37
  1. Write a function first_negative(numbers) that returns the position (index) of the first negative number in a list, or −1 if there isn't one.
Show the answer
def first_negative(numbers):
    for i, n in enumerate(numbers):
        if n < 0:
            return i
    return -1

print(first_negative([5, 3, -2, 8, -7]))
print(first_negative([1, 2, 3]))
2
-1

return works like a break that also leaves the function and hands back a value.

Interview questions

What is the difference between break, continue and pass?

break ends the whole loop. continue ends only the current iteration and moves to the next one. pass does nothing; it's a placeholder where Python needs a statement but you have no code to run.

How do you break out of nested loops in Python?

Python has no labelled break, so break exits only the innermost loop. The usual fixes are to move the loops into a function and return, or to set a flag variable and check it in the outer loop.

When does the else block of a for loop run?

When the loop finishes normally, by running out of items. It doesn't run if the loop ended with break. It's used for "not found" cases in searches.

Key takeaways

  • break stops the loop at once; Python continues after the loop.
  • continue skips to the next iteration; in a while loop, update the counter before it.
  • pass does nothing and fills an empty block so Python doesn't raise an IndentationError.
  • break exits only the innermost loop. To leave nested loops, use a function and return.
  • A loop's else block runs only when the loop wasn't stopped by break.

Frequently asked questions

Can I use break outside a loop?

No. Python raises SyntaxError: 'break' outside loop. To stop a function early, use return. To stop a whole script, use sys.exit().

Is using break bad practice?

No. It's normal Python and often clearer than a complicated loop condition. Avoid having many break statements scattered through one long loop, because that makes it hard to see when the loop ends.

Does pass do anything at run time?

No. Python runs it and moves to the next line without any effect. It exists only because Python's grammar needs at least one statement in an indented block.

What to learn next

  1. Put loops inside loops in nested loops and star patterns in Python.
  2. Handle many fixed choices neatly with the Python match statement.
  3. Revise conditions in Python if, elif and else.