[ Web Proxy ]
URL:
Viewing: https://www.pythonbyexample.dev/examples/loop-else [Back]  [Original]

Loop Else Python By Example Skip to main content Python By ExampleJourneysAbout
All examplesPython docs reference

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 skippedThe 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

Break and ContinueIterating over Iterables

Run the complete example

code:

Expected output

found
missing

Execution time appears here after you run the example.

adewale/pythonbyexample Python 3.13 docs Privacy
Web Proxy Viewer  |  New URL  |  Original Page