Module lessons (3/4)
break, continue, and else in loops
Exiting a loop early, skipping an iteration, and using Python’s for…else clause.
What you'll learn in this lesson
- Terminate the innermost loop early with
breakas soon as a search criterion is satisfied. - Skip a specific iteration without increasing nesting with
continue. - Master the
else:clause onfor/while, executed only if the loop did not encounterbreak.
Overview
Inside any for or while you can deviate from the linear flow with three powerful keywords: break to stop the loop right away, continue to move on to the next element, and else: on the loop to handle cases where no iteration has called break.
Imagine the else clause of a for as an "if no-break": whenever the loop reaches the natural end of the sequence without having executed break, it enters else. Conversely, if it hits break, it skips everything and continues after the entire construct.
Sections covered in this lesson
- 1The mental model: three exits from the cycle
- 2
breakvscontinueto keep the code linear - 3
for ... else:and nested loops - 4Quick check
- 5Test yourself
Unlock "break, continue, and else in loops" and the full Python Course curriculum
Exiting a loop early, skipping an iteration, and using Python’s for…else clause.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.