Python Reference ยท Statements and Keywords
The break and continue statements, and loop else
Reference for Python's break and continue statements and the else clause on for and while loops: exactly when each runs, nested loops, and search patterns.
Two statements steer a running loop. break leaves the innermost for or while loop immediately. continue abandons the rest of the current iteration and moves on to the next one (for while, the condition is tested again).
Python loops can also have an else clause, which runs when the loop finishes without hitting break. It is most useful for searches: the break means "found it", the else means "searched everything and did not".
for n in [1, 3, 5]: if n % 2 == 0: break else: print("no even number")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
for item in iterable: if skip_condition: continue if stop_condition: break ... else: ... # runs only if the loop was not ended by break
| Statement | Effect |
|---|---|
break |
Exits the innermost enclosing loop at once; the loop's else is skipped. |
continue |
Jumps to the next iteration of the innermost loop. |
else |
Runs after the loop's iterable is exhausted or the while condition becomes false. |
Both statements are a SyntaxError outside a loop. Inside a try with a finally block, the finally code still runs before the jump happens.
Usage notes
- Only the innermost loop. To leave nested loops, put them in a function and
return, set a flag, or usefor...elsewithcontinue/breakon the outer level. elsemeans "no break". It is not "otherwise if the loop did not run". It also runs for an empty iterable, and it is skipped afterreturnor an exception.- A
whileloop'selseruns when the condition goes false, not when you leave throughbreak. continueand counters. Inwhileloops, update the counter beforecontinue, or the same iteration repeats forever.- Readability.
for...elsesurprises many readers. A small helper function that returns early is often clearer, and a comment such as# no break: not foundhelps when you do use it. - Alternatives to
breaksearches:next((x for x in items if cond), default),any()andall(). continueinsidetry/finallyis allowed in every supported Python version; Python 3.14 additionally warns aboutreturn,breakorcontinuethat leave afinallyblock, because they silently swallow exceptions (PEP 765).