I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.
Consider the following:
if condition:
do_something()
else:
do_something_else()
Here, do_something_else()
is only executed if condition
is false, as expected.
Similarly, in
try:
do_something()
except someException:
pass:
else:
do_something_else()
finally:
cleanup()
do_something_else()
is only executed if no exception occurred.
But in for or while loops, an else clause is always executed, whether the contents of the for/while block
have been executed or not.
for i in some_iterator:
print(i)
else:
print("Iterator is empty!")
will always print "Iterator is empty!", whether I say some_iterator = []
or some_iterator = [1,2,3]
. Same behavior in while-else
clauses. It seems to me that else
behaves more like finally
in these cases. What am I overlooking?