for what are for/while else clauses

Fredrik Lundh fredrik at pythonware.com
Fri Nov 21 12:45:25 CET 2003


Mel Wilson wrote:

> >for a while-statement, the controlling condition is the test at
> >the top.
> >
> >for a for loop, the condition is "is there another item" (to quote the
> >language reference: "When the items are exhausted (which is imme-
> >diately when the sequence is empty) ... the loop terminates.".
> >
> >for a try-except clause, the condition is "did the suite raise an
> >exception".
>
>    Interesting way to think about it.  Thanks.
>
>    So in some sample code:
>
>         while some_condition:
>             some_action ()
>         else:
>             last_action ()
>         following_code ()
>
> If the loop results in some_action being done, say, 17
> times; then that means that some_condition was found true 17
> times.  The 18th time, some_condition is found to be false,
> the else takes effect and last_action gets done one time.

imagine a dialect of Python that supports C-style goto's and labels.
in this dialect,

        while some_condition:
            some_action ()
        else:
            last_action ()

can be rewritten as

  this_statement:
        if some_condition:
            some_action ()
            goto this_statement
        else:
            last_action ()
  next_statement:

(which, of course, is exactly what Python's current compiler does, but
on the bytecode level).

"break" and "continue" can now be rewritten as "goto next_statement"
and "goto this_statement".

for "for-in" and "try-except", the code calculating the "some_condition"
value is a bit different, but the rest works in exactly the same way.

here's the for-in version:

        <set up the iterator>
    this_statement:
        <fetch next value from iterator>
        if <value found>:
            variable = <value>
            some_action ()
            goto this_statement
        else:
            last_action ()
    next_statement:

and here's the try-except version (somewhat simplified):

    this_statement:
        <enable error handling>
        some_action ()
    error_handler:
        <disable error handling>
        if <matching error occurred>:
            some_action ()
        else:
            other_action ()

> The only wrinkle then is that the while loop construct
> passes control to the following code after that one
> last_action.  But we expect that from a while loop.

most Python statements pass control to the next statement
when they're done.

>    The effect of a break in the suite controlled by the
> while is to blow away execution of the whole while
> construct, including the else.
>
>    As an explanation, I like it.

me too.

</F>








More information about the Python-list mailing list