Control Flow
Loop Else
If the loop reaches break, the else block is skipped. This branch means the search succeeded early.
Source
names = ["Ada", "Grace", "Guido"]
for name in names:
if name == "Grace":
print("found")
break
else:
print("missing")Output
foundIf the loop finishes without break, the else block runs. This branch means the search examined every value and found nothing.
Source
for name in names:
if name == "Linus":
print("found")
break
else:
print("missing")Output
missingNotes
- Loop
elseruns when the loop was not ended bybreak. - It is best for search loops with a clear found/not-found split.
- It works with both
forandwhileloops.
See also
- related: Break and Continue
- related: For Loops
- related: While Loops
Run the complete example
Expected output
found
missing
Execution time appears here after you run the example.