While: else: (was Re: Working around a lack of 'goto' in python)
tjreedy at udel.edu
Tue Mar 9 19:49:05 CET 2004
"Jeff Epler" <jepler at unpythonic.net> wrote in message
news:20040309142924.GI12662 at unpythonic.net...
> > I think some of that could be alleviated through the use of 'else'
> > with 'for/while' although it looks like I need the opposite of its
> > semantics (a 'not else'). Quite frankly the existence of 'else'
> > in this context as a language feature baffles me and I don't use it.
> The same goes for me. I can never remember when the "else" clause will
> execute, and for that reason I'm very unlikely to use it.
It is ironic that these comments on while-else should arise in a thread on
if condition: something()
it is clear somethingelse executes when condition is false. If Python had
label and goto statements, one could write:
It is still clear that somethingelse executes when condition is or becomes
false. The difference is that something may be executed zero to many times
first. Also, barring an infinite loop, somethingelse is guaranteed to
execute. In today's real Python, we delete the label and goto and change
'if' to 'while' and write the above as
It may be less clear, but somethingelse still executes when condition is or
becomes false after zero to many executions of something (and
To complicate matters, add a second goto to the pseudoPython:
Now, somethingelse may be bypassed by the new goto. So it executes if and
when condition is or becomes false, which may or may not never happen. In
today's real Python, break is used instead for the same effect.
if comdition2: break
In the special case of iterating through a list, where the condition is
'there is another item in the list', this is condensed further to
for item in list
if comdition2: break
Again, somethingelse executes if and when the condition becomes false,
which is to say, when the list is exhausted (which maybe the reader is by
now), which process may be 'broken' by the break statement.
Terry J. Reedy
More information about the Python-list