for what are for/while else clauses
Bryan
belred1 at yahoo.com
Fri Nov 14 23:00:12 EST 2003
Terry Reedy wrote:
> "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
>
> 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
>
>
terry,
thnak you for your very clear and consice explanation.
bryan
More information about the Python-list
mailing list