6 of 6
break or continue Doesn't Run# β This print never happens for i in range(5): if i == 3: break print("This line is unreachable!") # Never runs!
# β Put the print BEFORE break for i in range(5): if i == 3: print("Stopping at 3!") break
Rule: Always put any code you want to execute before break or continue.
continue# β count never increases for skipped items count = 0 for item in items: if item == "skip_me": continue count += 1 # This only counts non-skipped items (might be what you want!)
Think about whether your counter should track all iterations or just the non-skipped ones.
while True Without a break# β Infinite loop β no way out! while True: print("Help, I'm stuck!")
# β Always have a break condition while True: answer = do_something() if answer == "done": break
Rule: Every while True loop must have a break somewhere inside it.
break When You Meant continuenumbers = [1, -2, 3, -4, 5] # β Stops at the first negative β only processes [1] for n in numbers: if n < 0: break print(n) # β Skips negatives β processes [1, 3, 5] for n in numbers: if n < 0: continue print(n)
break = "I'm done with this entire loop"continue = "Skip this one, keep going"| Situation | Use |
|---|---|
| Searching for something, stop when found | break |
| Filtering items, skip some but keep looping | continue |
| Loop until a condition is met (unknown iterations) | while True + break |
| Skip invalid data but process everything else | continue |
When your loop isn't behaving as expected, add a print at the top to see every iteration:
for i, item in enumerate(items): print(f"DEBUG: iteration {i}, item = {item}") # ... rest of your code
This helps you see if break is triggering too early or continue is skipping the wrong items.
Once you're comfortable with break and continue, try solving problems without them β using just loop conditions and if/else. Sometimes that's cleaner! The best programmers know when to use each approach.
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit