You're scanning ten million log lines for the first fatal error. Your for loop found it on line 2,041 — so why is it still reading the other 9,997,959? Because nobody told it to stop. Today you get the steering controls: stop now, skip this one, and do nothing (on purpose).
What you'll learn
What
break exits the current loop immediately. continue abandons the current iteration and jumps to the next one. pass does nothing at all — a placeholder where Python's syntax demands a statement but you have nothing to say yet.
Why
Without break, searches read everything even after finding the answer. Without continue, loops nest filter logic two and three levels deep. These two keywords are the difference between loops that state their intent and loops readers must decode.
Where it's used
Early exit from searches, skipping malformed records in data cleaning, stopping paginated API reads at the last page, and stubbing out unwritten branches during development.
Where this runs in production
Alert evaluators scan recent logs and break on the first line matching a critical pattern — evaluating millions of further lines would add latency to paging an engineer.
Photo pipelines iterate uploaded images and continue past corrupt or duplicate files, processing the rest of the batch instead of failing it.
Clients fetch results page by page in a while True loop and break when a page comes back empty — the natural shape when the total count is unknown.
readings = [98.1, 97.4, 103.8, 98.9]
for r in readings:
if r > 103.0:
print(f'ALERT: {r}')
break
print(f'ok: {r}')The loop prints 'ok' for the first two readings, hits 103.8, prints the alert, and break ends the loop — 98.9 is never examined. Search-and-stop: the signature use of break.
An inspector checks parts on a conveyor. continue is tossing a defective part into the reject bin and reaching for the next one — the line keeps moving. break is hitting the big red STOP button — the whole line halts, no further parts arrive. pass is standing at your station during a drill, hands visible, deliberately doing nothing.
The idiom `if <bad>: continue` at the TOP of a loop body works exactly like the guard clauses you met in Conditionals: dismiss the cases you can't process, then write the happy path underneath at a single level of indentation. Three guards beat three nested ifs every time.
values = ['12', '', 'N/A', '30']
total = 0
for v in values:
if not v.isdigit():
continue
total += int(v)
print(total) # 42The guard filters '' and 'N/A' out of the flow; only clean values reach the conversion. Note what continue skips: everything BELOW it in the body, for this iteration only.
In nested loops, break exits the innermost loop only — the outer loop continues. If you need to escape both, set a flag the outer loop checks, or better, move the nested loops into a function and return (functions arrive next module). Also beware the silent-skip trap: a continue that swallows bad records WITHOUT counting them hides data quality problems — keep a skipped counter.
Three keywords, three completely different jumps. Click each to see where execution lands.
Select a type to see its full definition, operations, and data science usage.
Find whether 'admin' appears in a user list — and stop looking once it does.
The loop checks 'sam', then 'admin' — match! break fires and 'lee' and 'kim' are never checked. Without break, the search would pointlessly continue.
checking sam checking admin found!
Your task
Scan a warehouse inventory feed. Skip entries with quantity 0 (out of stock — nothing to count), stop entirely at the 'END' marker, and total the units seen. Use continue, break, and the counters provided.
Units counted: 19 Skipped: 1
Write your solution in the editor on the right, then hit Run.
What does this print? for n in [1, 2, 3, 4]: if n == 3: break print(n)
What does this print? for n in [1, 2, 3, 4]: if n % 2 == 0: continue print(n)
Why does `while True:` with a mid-body break exist as an idiom instead of putting the test in the condition?
What was the design flaw?
Find the first number in nums = [7, 11, 4, 9, 12, 3] that is divisible by 4, print it, and stop scanning immediately. Expected output: 4
Inside the INNER loop of two nested for loops, break executes. What happens?
What's the correct minimal fix?
Explain break, continue, and pass, and give a production use for each.
break exits the nearest enclosing loop immediately — production use: scanning logs for the first fatal error, or reading API pages until an empty one. continue abandons the current iteration and jumps to the next — production use: skipping malformed records in a cleaning loop while the rest of the batch proceeds. pass is not loop control at all: it's a do-nothing statement that fills a syntactically-required block — production use: stubbing an unimplemented branch during a refactor or deliberately ignoring a specific exception. The one-line distinction I'd give: break ends the loop, continue ends the iteration, pass ends nothing.
A reviewer flags your `if bad: continue` data-cleaning loop as a silent-failure risk. What are they worried about, and how do you address it?
The skip itself is fine — the risk is that skips are invisible. If an upstream schema change suddenly makes half the records invalid, a bare continue drops them without a trace and the pipeline still reports success; the data downstream is quietly wrong, which is the worst failure mode in data engineering. The fix is cheap: increment a skipped counter (ideally per skip-reason), log a sample of rejected records, and alert when the skip RATE crosses a threshold. The principle behind it: every record entering a pipeline should be accounted for in the output — processed, skipped-with-reason, or failed — so totals reconcile.
How do you exit two levels of nested loops in Python, given that break only escapes one?
Three honest options. One: set a flag — found = True plus break inside, and make the outer loop's first statement `if found: break`; it works everywhere but adds bookkeeping. Two — usually best: extract the nested loops into a function and use return, which exits all levels at once and gives the search a name and a testable interface. Three: restructure so there's only one loop, for instance iterating over combinations directly. Python deliberately has no labeled break like Java; the language's answer is 'use a function'. In an interview I'd lead with the function approach and mention the flag as the quick local fix.
Common Mistakes to Avoid
1) Expecting break to exit ALL nested loops — it exits only the innermost. 2) Silent continue skips with no counter — data-quality regressions vanish. 3) Ordering guards wrong: the abort/break check belongs before the skip/continue check, or poison records get miscounted as skips. 4) A while True whose break is buried or conditional on something that may never happen — that's just an infinite loop with extra steps. 5) Using pass where you meant continue (pass falls through and RUNS the rest of the body). 6) Code after continue in the same block — it's unreachable for that iteration.
Ask the AI Tutor
Try these prompts in the AI Tutor panel: • 'Give me five loops using break/continue and quiz me on their output.' • 'Show a bug where pass was used instead of continue.' • 'Refactor this nested-if loop body into guard clauses with continue.' • 'When is while True considered clean code?' • 'Interview mode: ask me how to escape nested loops and grade my answer.'
Glossary
break — statement that exits the nearest enclosing loop immediately. continue — statement that skips the rest of the current iteration and returns to the loop's top. pass — a statement that does nothing; fills a syntactically-required empty block. Early exit — leaving a loop as soon as the answer is known. Guard (in a loop) — an `if bad: continue` line at the top of the body that filters out unprocessable items. Poison pill — a special record whose appearance must halt processing. while True — an intentionally endless condition paired with a mid-body break. .extend() — list method appending all elements of another list. .startswith() — string method testing a prefix.
Recommended Resources
• Docs: 'break and continue Statements' in the official Python tutorial. • Read: PEP 8 on when explicit is better than clever — guard clauses with continue are the loop-shaped example. • Practice: take the log-scanning Industry Example and add a third rule (count ERROR lines separately) without adding any nesting. • Next in DSM: you now steer loops line by line — List Comprehensions collapse the whole filter-and-transform loop into a single readable expression, the most Pythonic syntax you'll learn this module.
Recap
✓ break ends the loop; continue ends the iteration; pass ends nothing (placeholder). ✓ Both break and continue affect only the NEAREST enclosing loop. ✓ `if bad: continue` at the top of a body is the loop version of a guard clause. ✓ while True + break is the honest shape for fetch-then-decide loops like pagination. ✓ Count your skips — silent continue is how data-quality bugs hide. ✓ Escaping nested loops cleanly usually means extracting a function and returning. Next up: List Comprehensions. The filter-and-transform loops you've been writing in four lines collapse into one expressive line — Python's signature move for building new lists.
Run your code to see the output here.