for-else

rockingred willsteve2003 at yahoo.ca
Mon Mar 10 15:43:59 CET 2008


On Mar 8, 4:15 pm, "Terry Reedy" <tjre... at udel.edu> wrote:
> "egbert" <egbert.bouw... at hccnet.nl> wrote in message
>
> news:20080308152034.GA12009 at hccnet.nl...
> | However the loop-else really works more like this:
> | .  try to do the loop;
> | .  if it starts but is interrupted by a break,
> | .  then do something else as well.
>
> This is NOT how loop-else works for Python.
> If you want to do something special on breaks,
> put the break-only code before the break.
>
> while loop_condition:
>   <loop statements>
>   if break_condition:
>     <break-only statements>
>     break
>   <more loop stuff>
>
> | So they are completely different beasts, and if you try to use
> | or explain the one according to the rules of the other one,
> | you put a serious strain on your synapses.
>
> I did not mean to broke your brain.
>
> | The explanation that the if-else and the loop-else
> | follow the same pattern, runs more or less like this:
> | .  all conditions to run the loop to its completion were met,
> | .  which means that the loop-condition is not met (any more),
> | .  which means that we must do something else.
> | For me that is orwellian logic: success is failure.
>
> 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'.
>
> If the sense of else were reversed, one would have to write the clumbsier
>
> complete = True # though false at this point
> while loop_condition:
>   <loop statements>
>   if break_condition:
>     complete = False
>     break
>   <more loop stuff>
> else:
>   <break-only statements>
> if complete:
>   <completion-only statements>
>
> Terry Jan Reedy

Terry, instead of using "complete = True" and setting it to false on
failure, why not set "loop_completed = False" and set it to True if
the break condition is met?



More information about the Python-list mailing list