1 of 6
break and continueYou already know for and while loops. Now it's time to learn two powerful keywords that give you finer control over how your loops run.
break β Exit the Loop Earlybreak immediately stops the loop, even if the condition is still True or there are more items to iterate over.
for i in range(10): if i == 5: print("Found 5! Stopping.") break print(i)
Output:
0
1
2
3
4
Found 5! Stopping.
The loop was supposed to go to 9, but break ended it at 5.
break with while TrueA common pattern is to use while True (an infinite loop) and break to exit when a condition is met:
count = 0 while True: count += 1 if count > 3: break print(count) print("Done!")
Output:
1
2
3
Done!
This is useful when you don't know the exact stopping condition upfront, or when the exit check needs to happen in the middle of the loop body.
continue β Skip to the Next Iterationcontinue skips the rest of the current iteration and jumps back to the top of the loop.
for i in range(6): if i % 2 == 0: continue print(i)
Output:
1
3
5
Even numbers hit continue, so their print is skipped. The loop still runs all 6 times β it just doesn't execute the code after continue for those iterations.
You can combine break and continue in the same loop:
numbers = [4, -1, 7, 0, 3, -5, 8] total = 0 for num in numbers: if num < 0: continue # skip negatives if num == 0: break # stop at zero total += num print(total) # 11 (4 + 7)
| Keyword | What it does | When to use |
|---|---|---|
break | Exits the loop immediately | Searching for something, stopping early |
continue | Skips to the next iteration | Filtering out certain items |
while True + break | Loop until you decide to stop | Unknown number of iterations |
break and continue only affect the innermost loop they're inbreak or continue (in that iteration) does not runbreak exits the loop entirely β continue just skips one iterationβ 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