Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, December 8, 2015

python: Nonintuitive ELSE after FOR or WHILE

When I first saw an else clause after a for loop, I concluded that those were the steps to run if the condition inside the loop was never true-- that is, either you enter the loop or you do its else.
Wrong: Those are the steps to run if you exit the loop without a break statement. 

A better label would be NO_BREAK, but I understand not wanting to add keywords to the language. 

Test: Are the else steps executed when the loop is never entered?

for thing in ['abc','','tobreak','ok']:
    print "\nvertical [%s]" % thing
    for c in thing:
        print c
        if c=='r':
            break
    else:
        print "No r in [%s]" % thing

else:
    print "\nthat's all"

output

vertical [abc]
a
b
c
No r in [abc]

vertical []
No r in []

vertical [tobreak]
t
o
b
r

vertical [ok]
o
k
No r in [ok]

that's all

Process finished with exit code 0

No comments:

Post a Comment