Condition and Loops Style Notes
As additional syntax, the
for
and
while
statements permits an
else
clause. This is a suite of statements that are executed when the loop
terminates normally. This suite is skipped if the loop is terminated by a
break
statement. The
else
clause on
a loop might be used for some post-loop cleanup. This is so unlike other
programming languages, that it is hard to justify using it.
An
else
clause always raises a small problem when
it is used. It's never perfectly clear what conditions lead to execution
of an
else
clause. The condition that applies has to be
worked out from context. For instance, in
if
statements, one explicitly states the exact condition for all of the
if
and
elif
clauses. The logical
inverse of this condition is assumed as the
else
condition. It is, unfortunately, left to the person reading the program to
work out what this condition actually is.
Similarly, the
else
clause of a
while
statement is the basic loop termination
condition, with all of the conditions on any
break
statements removed. The following kind of analysis can be used to work out
the condition under which the else clause is executed.
while not BB:
if C1: break
if C2: break
else:
assert BB and not C1 and not C2
assert BB or C1 or C2
Because this analysis can be difficult, it is best to avoid the use
of
else
clauses in loop constructs.