Why is the purpose of the “else” clause following a “for” or “while” loop? [duplicate]

You are wrong about the semantics of for/else. The else clause runs only if the loop completed, for example, if a break statement wasn’t encountered.

The typical for/else loop looks like this:

for x in seq:
    if cond(x):
        break
else:
    print "Didn't find an x I liked!"

Think of the “else” as pairing with all of the “if’s” in the loop body. Your samples are the same, but with “break” statements in the mix, they are not.

A longer description of the same idea: http://nedbatchelder.com/blog/201110/forelse.html

Leave a Comment