Learn Python
>>> control_flow.loop_else
The for-else and while-else Clause in Python
#concept
Both for and while loops can have an attached else block — a feature unusual enough that it surprises people coming from other languages. The else block runs only if the loop finished naturally, without being cut short by a break. It's most useful for "search, and report if nothing was found" patterns.
#how it works
1
Write a normal for or while loop
Nothing different from any other loop so far.
2
Add an else: block afterward
At the same indentation level as the loop itself.
3
If the loop completes without a break
The else block runs.
4
If a break fires at any point
The else block is skipped entirely, no matter when the break happened.
5
This else means something different from usual
"The loop finished on its own," rather than the ordinary if/else meaning.
#example
numbers = [2, 4, 6, 8] for n in numbers: if n % 2 != 0: print(f"Found an odd number: {n}") breakelse: print("All numbers are even")Output
All numbers are even
1The loop checks each number in turn for oddness — none of 2, 4, 6, 8 are odd, so break never fires.
2Because the loop completed every iteration without breaking, the else block runs, printing "All numbers are even".
3If the list had included an odd number, break would have fired on finding it, and the else block would have been skipped entirely.
#use cases
Searching a list for something and cleanly reporting 'not found' only if the search truly came up empty
Validating that every item in a collection passes a check, with a special message only if all of them did
Replacing a separate found flag variable that would otherwise need to be set and checked manually
Loop-based algorithms that need a clear 'completed without early exit' signal
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.