for what are for/while else clauses

Michael Chermside mcherm at mcherm.com
Mon Nov 17 18:45:55 CET 2003


Fredrik Lundh writes:
> the break statement has nothing to do with the else clause; the else
> is executed when there's no more item in the sequence.  if you break
> or raise or return or yield-and-never-resume or call-and-never-return
> your way out of the loop doesn't matter.
> 
> read the C code if you don't believe me.
   [...]
> for a while-statement, the controlling condition is the test at
> the top.

Fredrik, I didn't try to go read the C code... instead I experimented
in Python:

    def testWhileElse(exitViaBreak, condTrueAtExit):
        print
        print 'exitViaBreak = %s' % exitViaBreak
        print 'condTrueAtExit = %s' % condTrueAtExit
        if exitViaBreak:
            loopCond = False
        else:
            loopCond = True
        while loopCond:
            if condTrueAtExit:
                loopCond = True
            break;
        else:
            print 'executed else clause'

According to this experiment, the only way to get "executed else clause"
to print is to set exitViaBreak to True. So I really don't understand
what you are claiming. Seems to me that the execution of the else
does NOT depend on the status of the loop condition at exit.

Besides which... the point made by Alex (among others) is a good one:
it doesn't matter how it's implemented under the covers... what matters
is how the writer/reader thinks of the code. And I've always thought
of the "else" on loops as having to do with the use or non-use of break
statements. And in this particular case I suspect that's how MOST Python
programmers think of it.

-- Michael Chermside






More information about the Python-list mailing list