While: else: (was Re: Working around a lack of 'goto' in python)

Terry Reedy 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
goto.  In:

if condition: something()
else: somethingelse()

it is clear somethingelse executes when condition is false.  If Python had
label and goto statements, one could write:

label: start
if condition:
  something()
  modify_condition_vars()
  goto: label
else: somethingelse()

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

while condition:
  something()
  modify_condition_vars()
else: somethingelse()

It may be less clear, but somethingelse still executes when condition is or
becomes false after zero to many executions of something (and
modify_condition_vars).

To complicate matters, add a second goto to the pseudoPython:

label: start
if condition:
  something()
  if condition2:
    goto: done
  modify_condition_vars()
  goto: label
else: somethingelse()
label: done

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.

while condition:
  something()
  if comdition2: break
  modify_condition_vars()
else: somethingelse()

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
  something()
  if comdition2: break
else: somethingelse()

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 mailing list