for what are for/while else clauses

Fredrik Lundh fredrik at pythonware.com
Tue Nov 18 11:01:55 EST 2003


Michael Chermside wrote:

> According to this experiment, the only way to get "executed else clause"
> to print is to set exitViaBreak to True.  So I really don't understand what
> you are claiming. Seems to me that the execution of the else does NOT
> depend on the status of the loop condition at exit.

That's not what your program shows, though: if you set "exitViaBreak"
to true, your program sets the loop condition to false *before* it enters
the loop.  In other words, your experiment shows that the else clause
runs when the loop condition is found to be false, and that it only runs
in that case.

Maybe you should read the C code, after all?

Or maybe this quote from a popular python book might help:

    "Both the while and for statement may optionally have a trailing
    else clause. The statement or statements after the else execute
    when the loop terminates naturally (at the end of the for iterator
    or when the while loop condition becomes false), but not when
    the loop terminates prematurely (via break, return, or an exception).

(the author seems to have rebooted since he wrote that, though.)

</F>








More information about the Python-list mailing list