for-else

Carl Banks pavlovevidence at gmail.com
Mon Mar 10 10:39:35 EDT 2008


On Mar 8, 5:15 pm, "Terry Reedy" <tjre... at udel.edu> wrote:
> I gave a clear and coherent explanation of how while derives from if,
> and correspondingly, how while-else derives from if-else, to help those who
> want to read and write Python code.  Building on the pseudo-snippet above,
> one can write
>
> while loop_condition:
>   <loop statements>
>   if break_condition:
>     <break-only statements>
>     break
>   <more loop stuff>
> else:
>   <completion-only statements>
>
> Python allows one to have both break-only and completion-only sections
> together in one compound statement and *without* having to fiddle with a
> special flag variable.  I am sorry if you cannot appreciate such elegance
> and can only spit on it as 'orwellian'.


Just to play Devil's advocate, there is one draw drawback to "such
elegance": when there are multiple break statements.  Which means
you'd have to duplicate the break-only condition, or refactor somehow
(which may or may not be suitable).

There have been a couple occasions where I felt the best solution was
to a temporary varible like so:

completed = False
while loop_condition:
    <loop statements>
    if break_condition:
        break
    <more loop stuff>
    if some_other_break_condition:
        break
    <more loop stuff>
else:
    completed = False
if not completed:
    <break-only statements>

It felt icky but we're all still here so it couldn't have been that
bad.


Carl Banks



More information about the Python-list mailing list