"Diez B. Roggisch" <de************ @web.de> wrote in message
news:bp******** *****@news.t-online.com...
I imagined that the else-clause would only be executed if the loop
body wasn't entered, so I could write this
.... waiting for enlightment,
Try the following which I recently thought up.
You are familiar with this:
if cond: t()
else: f()
meaning, if cond is false, do f(). Now
while cond: t()
else: f()
means if and when cond is false, do f(). To make the parallel
clearer, consider this C-like pseudopython equivalent:
label: loop
if cond:
t()
goto loop
else: f()
If (and now when, because of the looping) cond is false, do f(). Now,
for i in seq: t()
else: f()
translates to something like
__i, __istop = 0, len(seq)
while __i < __istop:
i = seq[__i]
t()
else: f()
which in turn could be translated to an if with goto, so that f
executes if/when the sequence is exhausted.
In summary, the else clause executes if/when the loop condition
evaluates as false, just as with else clauses and if conditions. The
difference is the repeated instead of just once testing of the
condition. Break aborts this repeated testing and bypasses the else
clause, as it should because the condition was always true, as also
happens with true if conditions.
Terry J. Reedy