for/else and while/else
An else attached to a loop, which runs only when the loop was never broken out of - and is misread by almost everyone the first time.
Overview
The rule, exactly
for item in items:
if item == target:
break
else:
print("not found")
The else runs if the loop ran to completion without hitting break. Iterate zero times? The else runs. Iterate a million times and finish? The else runs. Break out on the first pass? It does not.
The keyword is badly chosen. If it were called nobreak, nobody would ever have been confused by it, and reading it that way in your head is the fastest way to make it click.
loop_else.py
loop_else_uses.py
Worth knowing
else runs when the loop ended normally - no break.