When should I use `break` versus `continue` in a Python loop?
Quick answer
break exits the nearest enclosing loop, so use it when you have found what you were searching for and do not need to scan further. continue skips the rest of the current loop cycle and moves to the next one, so use it to ignore an item while still checking later items. Both statements affect only the innermost loop when loops are nested. [S1]
The question, the details, the next step.
A practical checklist
State whether you want to stop the nearest loop or skip just the current item.
For a search that is finished at the first match, use
break.For a filter that rejects one item but must examine later items, use
continue.Trace what happens to the item immediately after a match or skip.
In nested loops, check which indented loop contains the statement; it affects the innermost enclosing loop.
A few more useful answers
Does `continue` end the loop?
No. It skips the rest of the current cycle and moves to the next cycle of the nearest enclosing loop. [S1]
Does `break` stop every loop when loops are nested?
No. It terminates only the nearest enclosing loop, which is the innermost loop containing it. [S1]
What happens if a search loop never finds its target?
The loop completes without reaching a break triggered by the match. Add separate logic if your program should report that no match was found.
Sources
References used for this guide.
- [S1] Python Language Reference: The break and continue statements docs.python.org · Checked
