for what are for/while else clauses
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
> Interesting way to think about it. Thanks.
> So in some sample code:
> while some_condition:
> some_action ()
> 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,
can be rewritten as
(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>
<fetch next value from iterator>
if <value found>:
variable = <value>
and here's the try-except version (somewhat simplified):
<enable error handling>
<disable error handling>
if <matching error occurred>:
> 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.
More information about the Python-list