for what are for/while else clauses
tjreedy at udel.edu
Sat Nov 15 01:35:46 CET 2003
"Diez B. Roggisch" <deets_noospaam at web.de> wrote in message
news:bp371c$g75$07$1 at news.t-online.com...
> I imagined that the else-clause would only be executed if the loop
> 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()
meaning, if cond is false, do f(). Now
while cond: t()
means if and when cond is false, do f(). To make the parallel
clearer, consider this C-like pseudopython equivalent:
If (and now when, because of the looping) cond is false, do f(). Now,
for i in seq: t()
translates to something like
__i, __istop = 0, len(seq)
while __i < __istop:
i = seq[__i]
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
More information about the Python-list