break, continue & the loop-else
Beginnerbreak exits a loop, continue skips to the next iteration, and Python's unusual for...else runs the else block only when the loop finished WITHOUT break — perfect for search loops.
Overview
break and continue behave as in Java. Python adds a twist almost no other language has: loops can have an else clause that executes only if the loop ran to completion (no break). It reads oddly at first — think of else as "nobreak" — but it eliminates the found-flag pattern in search loops. Interviewers use it to check whether you actually know Python or just write Java in Python syntax.
break & continue
Use continue to skip unwanted items early (a guard inside the loop) and break to stop when the answer is found — both keep loop bodies flat.
# continue — skip invalid rows early
rows = ["12", "", "7", "abc", "30"]
total = 0
for r in rows:
if not r.isdigit(): # skip blanks & junk
continue
total += int(r)
print(total) # 49
# break — stop at first match
primes = [2, 3, 5, 7, 11, 13]
target = 7
for p in primes:
if p == target:
print("found", p)
breakfor...else — "no break happened"
The else block runs when the loop exhausts naturally. Classic use: search loops — the else is your "not found" branch, no boolean flag needed.
# WITHOUT for-else — flag variable (clunky)
found = False
for user in ["asha", "ravi"]:
if user == "admin":
found = True
break
if not found:
print("admin missing")
# WITH for-else — clean
for user in ["asha", "ravi"]:
if user == "admin":
print("admin present")
break
else: # runs ONLY if no break fired
print("admin missing")
# Real example: prime check
n = 29
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
print("not prime")
break
else:
print(n, "is prime") # loop completed -> no divisor foundKey Points to Remember
- 1break exits the nearest enclosing loop only (no labeled breaks — refactor to a function and return)
- 2continue jumps to the next iteration — great for guard conditions
- 3for...else / while...else: else runs only if NO break occurred
- 4Need to break out of nested loops? Extract to a function and return
Interview Questions
Sign in to ask AriaWhen does the else block of a for loop execute? Give a practical use case.
Python has no labeled break like Java — how do you exit nested loops cleanly?
Ask Aria about break, continue & the loop-else
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.