for-else
Terry Reedy
tjreedy at udel.edu
Sat Mar 8 16:15:31 EST 2008
"egbert" <egbert.bouwman 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
More information about the Python-list
mailing list