Python Loop else: Detect Unsuccessful Searches
Core idea
A loop may have an else: aligned with its for or while header. The else body runs when a for loop exhausts its items or a while condition becomes false, including when there are zero iterations. A break from that loop skips its else. This is useful for reporting a search with no match. An exception or a function return that exits the loop also prevents reaching the else.
for code in ["K2", "M4", "R8"]: if code == "M4": print("Found") breakelse: print("Missing")The match triggers break, so the loop else is skipped.
Search has no match
for code in ["K2", "R8"]: if code == "M4": print("Found") breakelse: print("Missing")All items are visited without break. The else runs once, not once per failed comparison.
While condition starts false
remaining = 0while remaining > 0: remaining = remaining - 1else: print("Complete")The condition is false immediately. Normal completion still runs the else.
Common mistake
An else indented to match an inner if belongs to that if, not to the loop. Align loop else with the loop header. A continue alone does not suppress loop else.
Practice
Search for "X" in a list of codes using for, break and else. Try a match, no match and an empty list.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loop else and searches
Check your understanding of loop else.
What is printed?
for c in []: if c == "X": breakelse: print("Missing")What is printed?
for c in "AX": if c == "X": print("Found") breakelse: print("Missing")What is printed?
for n in range(2): if n == 0: continueelse: print("Done")Where is a for-loop else aligned?