Tutorials Python Python break & continue
Ch 17 / 58
Python Beginner 8 min read Chapter 17 of 58

Python break & continue

break and continue are loop control statements that let you alter the default flow of any loop. break exits the loop entirely — perfect for stopping a search once you've found your target. continue skips the rest of the current iteration and jumps to the next — ideal for filtering out unwanted values. Together with pass, they give you complete, fine-grained control over loop execution. This chapter covers all three with visual flow diagrams, real-world examples, and the tricky edge cases every developer must know.

What you'll learn in this chapter
break — exit a loop immediately with flow diagram
continue — skip an iteration with flow diagram
pass — the no-operation placeholder
break and continue in for vs while loops
Nested loops — break only exits the innermost loop
Real-world patterns and common pitfalls
Advertisement

What Are Loop Control Statements?

Loop control statements modify the execution of a loop beyond the simple "run the body, check the condition, repeat" cycle. Python provides three: break, continue, and pass. They work inside both for and while loops.

Key rule In a nested loop, break and continue only affect the innermost loop they appear in. They do not jump out of multiple levels at once.
break
Exit the loop immediately
continue
Skip current iteration only
pass
Do nothing — placeholder

The break Statement

When Python encounters break inside a loop, it immediately exits the loop — no further iterations occur, and control passes to the first statement after the loop. It's the "stop everything and get out" command. The loop's else block (if present) is skipped when break fires.

break — Control Flow Diagram
▶ Start Loop
↓
Check condition
↙ True
↘ False
Execute body
↓
break condition?
Yes ↓
⛔ break
No ↑
Next iteration
◼ Exit loop
↓
◼ Code after loop
Python — break_statement.py
# break in a for loop
for i in range(10):
    if i == 5:
        break          # stop when i reaches 5
    print(i, end=" ")
# 0 1 2 3 4
print("\nAfter loop")   # always runs

# break in a while loop
n = 0
while True:           # infinite loop — exit via break
    n += 1
    if n > 4:
        break
    print(n, end=" ")
# 1 2 3 4

# Search and stop — most common real use case
students = ["Alice", "Bob", "Carol", "Dave"]
target   = "Carol"

for idx, name in enumerate(students):
    if name == target:
        print(f"Found '{target}' at index {idx}")
        break           # no need to check remaining
# Found 'Carol' at index 2

# break + else — else runs only when no break occurred
for n in [1, 3, 5, 7]:
    if n % 2 == 0:
        print("Found even!")
        break
else:
    print("No even number found")  # runs — no break
break
Exits the innermost loop immediately. Code after the loop still runs. The loop's else clause is skipped.
for...else with break
The else block is your "not found" handler — it only runs if the loop completes without any break. Classic search pattern.
while True + break
The standard Python idiom for a do-while loop or interactive menu — loop forever but exit explicitly with break when done.

The continue Statement

When Python encounters continue, it skips the rest of the current iteration and immediately moves to the next one — re-checking the loop condition (for while) or advancing to the next element (for for). The loop does not exit; it just skips one step. Use it to filter out items you don't want to process.

continue — Control Flow Diagram
▶ Start Loop
↓
Check condition
↓ True
Execute body
↓
continue condition?
Yes ↑
⏭ continue
→ back to top
No ↓
Rest of body
↓
Next iteration ↑
→ False
◼ Exit loop
Python — continue_statement.py
# continue in a for loop — skip even numbers
for i in range(10):
    if i % 2 == 0:
        continue        # skip even, don't print
    print(i, end=" ")
# 1 3 5 7 9

# continue in a while loop
i = 0
while i < 10:
    i += 1             # ← update BEFORE continue!
    if i % 3 == 0:
        continue        # skip multiples of 3
    print(i, end=" ")
# 1 2 4 5 7 8 10

# Skip invalid / empty values
data = ["Alice", "", "Bob", None, "Carol", "  "]
for item in data:
    if not item or not item.strip():
        continue        # skip empty/None/whitespace
    print(item.upper())
# ALICE  BOB  CAROL

# Skip negative numbers — sum positives only
nums  = [4, -2, 7, -1, 3, -8, 5]
total = 0
for n in nums:
    if n < 0:
        continue        # skip negatives
    total += n
print(f"Sum of positives: {total}")  # 19
continue in while — update before continue! In a while loop, if your counter update (i += 1) comes after a continue, it will be skipped every time continue fires — creating an accidental infinite loop. Always increment before the continue.
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

The pass Statement

pass is the null operation — it does absolutely nothing when executed. It exists solely as a syntactic placeholder for situations where Python's grammar requires a statement but you have no code to write yet. It's used during development to stub out empty blocks.

Python — pass_statement.py
# pass in a loop — placeholder body
for i in range(5):
    pass               # TODO: implement later; loop body required

# Without pass this would cause SyntaxError:
# for i in range(5):
# ↑ IndentationError: expected an indented block

# pass in a conditional
x = 42
if x > 0:
    pass               # handle positive later
else:
    print("Non-positive")

# pass in a function stub
def train_model():
    pass               # implement when ready

# pass in a class stub
class DatabaseConnection:
    pass               # fields and methods to be added

# pass inside a try/except to silently ignore
try:
    int("not a number")
except ValueError:
    pass               # intentionally ignored

# pass vs continue — KEY difference
print("-- pass --")
for i in range(3):
    if i == 1: pass    # does nothing — execution continues below
    print(i)            # 0 1 2  (all printed)

print("-- continue --")
for i in range(3):
    if i == 1: continue  # skip rest of body for i==1
    print(i)              # 0 2  (1 is skipped)
pass vs continue pass does nothing and the rest of the body continues to execute. continue actively skips the remaining body and jumps to the next iteration. They look similar in a one-liner but behave very differently when code follows them in the block.

break & continue in Nested Loops

In nested loops, break and continue only affect the innermost loop they are placed in. They cannot jump out of multiple loops at once. To exit multiple levels, you need a flag variable, a function return, or a custom exception.

Python — nested_loop_control.py
# break only exits INNER loop
for i in range(1, 4):         # outer loop
    for j in range(1, 4):     # inner loop
        if j == 2:
            break            # exits inner, outer continues
        print(f"({i},{j})", end=" ")
    print()
# (1,1)
# (2,1)
# (3,1)

# continue only skips CURRENT inner iteration
for i in range(1, 3):
    for j in range(1, 4):
        if j == 2:
            continue         # skip j==2 only
        print(f"({i},{j})", end=" ")
    print()
# (1,1) (1,3)
# (2,1) (2,3)

# ✅ Exit BOTH loops — use a flag variable
found = False
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for row in matrix:
    for val in row:
        if val == 5:
            found = True
            break            # exit inner loop
    if found:
        break              # also exit outer loop
print(f"Found 5: {found}")   # Found 5: True

# ✅ Even cleaner — wrap in a function and return
def find_value(matrix, target):
    for r, row in enumerate(matrix):
        for c, val in enumerate(row):
            if val == target:
                return (r, c)  # exits ALL loops at once
    return None

print(find_value(matrix, 5))   # (1, 1)

break vs continue vs pass — Side-by-Side

The three loop control statements serve completely different purposes. Here's a clear side-by-side comparison to cement the distinction:

Statement Effect on loop Remaining body runs? Loop else runs? Loop continues?
break Exits loop immediately
No
No — skipped
No — loop ends
continue Skips current iteration
No
Yes (if finishes)
Yes — next iteration
pass Does nothing
Yes
Yes
Yes — normal flow
Python — comparison_demo.py
# All three with i==3 — spot the difference
print("=== break ===")
for i in range(6):
    if i == 3: break
    print(i, end=" ")
# 0 1 2  ← stopped at 3

print("\n=== continue ===")
for i in range(6):
    if i == 3: continue
    print(i, end=" ")
# 0 1 2 4 5  ← 3 skipped

print("\n=== pass ===")
for i in range(6):
    if i == 3: pass
    print(i, end=" ")
# 0 1 2 3 4 5  ← all printed (pass does nothing)

Real-World Patterns

Here are the most common professional patterns that use break and continue — you'll encounter all of these in real Python codebases:

Python — real_world_patterns.py
# ── Pattern 1: First-match search (break) ───────────
def find_first(items, predicate):
    for item in items:
        if predicate(item):
            return item        # same effect as break in a function
    return None

first_even = find_first([1,3,4,6], lambda x: x%2==0)
print(first_even)          # 4

# ── Pattern 2: Input validation (break) ─────────────
while True:
    score = input("Enter score (0-100): ")
    if score.isdigit() and 0 <= int(score) <= 100:
        break
    print("Invalid. Enter a number 0–100.")
print(f"Score accepted: {score}")

# ── Pattern 3: Filter pipeline (continue) ───────────
log_lines = [
    "INFO: server started",
    "DEBUG: loading config",
    "ERROR: disk full",
    "DEBUG: request received",
    "ERROR: memory low",
]
errors = []
for line in log_lines:
    if not line.startswith("ERROR"):
        continue           # skip non-errors
    errors.append(line)
print(errors)
# ['ERROR: disk full', 'ERROR: memory low']

# ── Pattern 4: Prime checker (break + else) ─────────
def is_prime(n):
    if n < 2: return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False   # divisor found — not prime
    return True             # no divisor — is prime

primes = [n for n in range(2, 30) if is_prime(n)]
print(primes)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

# ── Pattern 5: Skip processed items (continue) ──────
processed_ids = {101, 103, 105}
all_orders    = [101, 102, 103, 104, 105, 106]
for order_id in all_orders:
    if order_id in processed_ids:
        continue           # already done — skip
    print(f"Processing order {order_id}")
# Processing order 102
# Processing order 104
# Processing order 106

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all break, continue, and pass examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every loop control statement instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • break exits the current loop immediately — no more iterations. Code after the loop still runs. The loop's else block is skipped.
  • continue skips the rest of the current iteration and jumps to the next one. The loop continues; only one step is skipped.
  • pass is a no-operation placeholder — it does nothing. The rest of the loop body continues normally. Use it to stub out empty blocks during development.
  • In a while loop, always place the counter update before any continue — otherwise the counter never advances, creating an infinite loop.
  • In nested loops, break and continue only affect the innermost loop. Use a flag variable or wrap in a function to exit multiple levels.
  • The for...else / while...else clause runs only when the loop completes without a break — ideal for "not found" handlers.
  • Common break patterns: first-match search, input validation, interactive menu, retry logic.
  • Common continue patterns: skip invalid/empty values, filter log lines, skip already-processed items.
⚡
Free Resource
Download our Python break & continue Cheat Sheet
break / continue / pass comparison, flow diagrams, nested loop tips & real-world patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

break causes Python to exit the loop entirely. No further iterations occur; control moves to the first statement after the loop. It's like pressing "Stop" — the loop is done.

continue causes Python to skip the remainder of the current iteration only and jump to the next one. The loop is not exited; it continues with the next element (for) or re-checks the condition (while). It's like pressing "Skip" — just this step is missed.

for i in range(5):
    if i == 3: break
    print(i)   # 0 1 2  (stops at 3)

for i in range(5):
    if i == 3: continue
    print(i)   # 0 1 2 4  (skips 3)
✓ Answer

No. When a loop exits because of a break, the else clause is skipped entirely. The else block only runs when the loop completes naturally — i.e., the condition becomes False (while loop) or all elements are exhausted (for loop) without any break being triggered. This is the key pattern for "search and report not found":

for n in [1, 3, 5]:   # all odd
    if n % 2 == 0: break
else:
    print("No even found")  # ← prints (no break)
✓ Answer

pass is a null operation — it does nothing and execution falls through to the rest of the loop body. continue actively skips all remaining code in the current iteration.

for i in range(3):
    if i == 1: pass      # does nothing
    print(i)              # 0 1 2  ← all printed

for i in range(3):
    if i == 1: continue  # skips print below
    print(i)              # 0 2  ← 1 skipped
✓ Answer

break only exits the innermost loop it is placed in. The outer loop continues its iterations normally. To exit multiple levels of nesting, use one of these approaches:

  • Flag variable: set a boolean flag on break and check it in the outer loop.
  • Wrap in a function: use return inside the function — exits all loops at once.
  • Exception: raise a custom exception and catch it outside the loops (rare, not recommended).
✓ Answer

When continue executes, Python immediately jumps back to the top of the while loop to re-check the condition. Any code below continue in the body is skipped. If the counter update (i += 1) is placed after continue, it will be skipped every time continue fires — the counter never changes, the condition stays True, and you have an infinite loop:

# ❌ Infinite loop — i stuck at 3
i = 0
while i < 5:
    if i == 3: continue  # i never increments!
    i += 1               # never reached when i==3

# ✅ Correct — update before continue
i = 0
while i < 5:
    i += 1               # always increments
    if i == 3: continue  # now safe to skip
    print(i)
MCQ 1 of 3
What is the output of: for i in range(5): if i==3: break; print(i, end=" ")?
MCQ 2 of 3
What is the output of: for i in range(5): if i==3: continue; print(i, end=" ")?
MCQ 3 of 3
In a nested for loop, what does break in the inner loop do?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel