← Back to Python Course | Chapter 3: Control Flow | Lesson 7 of 10

Python break & continue

The Break Statement

break immediately exits the nearest enclosing loop, skipping any remaining iterations entirely — useful the moment you've found what you were searching for and there's no reason to keep checking the rest.

Example: The Break Statement

python
for n in [1, 2, 3, 4]:
    if n == 3:
        break
    print(n)

The Continue Statement

continue skips only the rest of the current iteration and jumps straight to the loop's next check, rather than ending the loop entirely the way break does — handy for filtering out cases you want to ignore without restructuring the loop body around an if.

Example: The Continue Statement

python
for n in [1, 2, 3, 4]:
    if n == 2:
        continue
    print(n)

While Loop with Break

Combining break with a while True: loop is a common pattern for "loop until some condition is met," letting the exit condition live anywhere inside the loop body instead of only in the loop's header.

Example: While Loop with Break

python
while True:
    print("Looping once")
    break

While Loop with Continue

When using continue inside a while loop, make sure any counter update happens *before* the continue line — otherwise the counter never advances for skipped iterations, and the loop runs forever.

Example: While Loop with Continue

python
i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

Else Block in Loops

A loop's optional else block runs only if the loop finished all its iterations without ever hitting a break — a lesser-known feature that's useful for search loops where you want to know whether the target was actually found.

Example: Else Block in Loops

python
for n in [1, 2, 3]:
    if n == 5:
        break
else:
    print("Never broke out")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.