Chapter 25 of 26

break & continue in Python

When working with loops, sometimes we don't want the loop to simply run from beginning to end.

We may want to stop the loop completely or skip one iteration. Python provides two useful statements for this:

  • break → stops the loop

  • continue → skips the current iteration

Let's see how they work.

break Statement

The break statement immediately stops the loop, even if the loop could continue running.

For example:

for number in range(1, 10):
    if number == 5:
        break

    print(number)

Output:

1
2
3
4

When number becomes 5, break stops the loop completely.

break with while

break also works with while loops:

count = 1

while count <= 10:
    if count == 5:
        break

    print(count)
    count += 1

Output:

1
2
3
4

Even though the condition is count <= 10, the loop stops early because of break.

continue Statement

The continue statement skips the current iteration and moves to the next one.

For example:

for number in range(1, 6):
    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

When number is 3, Python skips the rest of that iteration and continues with 4.

The loop itself does not stop.

break vs continue

The easiest way to remember the difference:

Statement

What it does

break

Stops the entire loop

continue

Skips only the current iteration

Think of it like this:

break     → 🚪 Leave the loop
continue  → ⏭️ Skip this round

Practical Example with break

Suppose we're searching for a particular number:

numbers = [10, 20, 30, 40, 50]

for number in numbers:
    if number == 30:
        print("Number found!")
        break

Output:

Number found!

Once 30 is found, there's no reason to continue searching, so break is useful here.

Practical Example with continue

Suppose we want to print only odd numbers:

for number in range(1, 6):
    if number % 2 == 0:
        continue

    print(number)

Output:

1
3
5

When the number is even, continue skips it.

break and continue in Nested Loops

When you use these statements inside nested loops, they affect the nearest loop they are inside.

for i in range(3):
    for j in range(3):
        if j == 1:
            break

        print(i, j)

Here, break stops the inner for loop, not the outer one.

Similarly, continue skips an iteration of the loop in which it appears.

A Real-World Example

Imagine a program processing orders. We want to stop when we encounter a cancelled order:

orders = ["Order 101", "Order 102", "Cancelled", "Order 104"]

for order in orders:
    if order == "Cancelled":
        break

    print("Processing:", order)

Output:

Processing: Order 101
Processing: Order 102

The loop stops when it reaches the cancelled order.

In Short

Use break when you want to say:

"Stop the loop now."

Use continue when you want to say:

"Skip this one and move to the next iteration."

These two statements give you much more control over how your loops behave.