for-else

castironpi at gmail.com castironpi at gmail.com
Mon Mar 10 17:39:59 CET 2008


> > The idea of the if-else is:
> > .  depending on some condition either do this or do something else,
> > .  don't do them both.
>
> constructs, I asked myself whether the application of a different idea
> resulted in a consistent, sensible interpretation.

They could just as easily have defined the else of a 'for' to mean 'if
the loop only completed not an even number of times', giving these
different outputs:

for a in [1,2,3,4,5]:
   if a> 3:
      break
else:
   print( 'bogus' )

for b in [1,2,3,4,5]:
   if b> 4:
      break
else:
   print( 'foo' )

Just as easily, yes.  Just as well?  Just as meaningfully?  Just as
consistently, usefully, and sensibly?

Possibly.  The meaning of 'if a loop' could be construed to mean a
parity test or a binary test (if it didn't even complete once, i.p. if
the sequence was empty).  If I tell you to do a loop, and then asked
if you did it, what factors in to your answer?

The docs say, 'A break statement executed in the first suite
terminates the loop without executing the else clause's suite', for
both for- and while-.

Does for-and and while-and or for-ifso and while-ifso sound more to
your liking?



More information about the Python-list mailing list