Control Flow

Loop Else

A loop else block runs only when the loop did not end with break.

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

found
loop bodyfell through · else runsbroke · else skipped
The loop's else branch runs only when the loop falls through naturally; break skips it.

If 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

missing

Notes

See also

Run the complete example

Example code

Expected output

found
missing

Execution time appears here after you run the example.