While: else: (was Re: Working around a lack of 'goto' in python)
Terry Reedy
tjreedy at udel.edu
Tue Mar 9 14:26:03 EST 2004
"Terry Reedy" <tjreedy at udel.edu> wrote in message
news:c2l3j0$6q7$1 at sea.gmane.org...
> 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).
Add: At this point, the else: is useless since the same would be true if
it were omitted. However ...
> 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