Else statement executing when it shouldnt

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jan 23 00:22:53 CET 2013


On Tue, 22 Jan 2013 16:48:35 +0100, Thomas Boell wrote:

> On Wed, 23 Jan 2013 02:42:27 +1100
> Chris Angelico <rosuav at gmail.com> wrote:
> 
>> On Wed, Jan 23, 2013 at 2:39 AM, Thomas Boell <tboell at domain.invalid>
>> wrote:
>> > Huh?! I would have expected all your examples to raise a SyntaxError
>> > or IndentationError. Why don't they? Is 'else' not required to have a
>> > matching 'if'?
>> 
>> Other things can have else, including 'for' and 'while' loops. :)
> 
> I must say, that's bound to be confusing for anyone who knows any
> language other than Python (or none, even).  Syntax like that is "an
> accident waiting to happen"...

Oh it's even worse than that. I reckon that nearly everyone thinks that 
for...else runs the "else" clause if the for loop is empty, at least the 
first time they see it. Or for the slow of thinking like me, the first 
few dozen times.

# this is wrong, but it looks right
for x in sequence:
    do_something_with(x)
else:
    print "sequence is empty"


But no, that's not what it does. `for...else` is actually more like this:


# this is right
for x in sequence:
    do_something_with(x)
    if condition:
        break
else:
    print "condition was never true"


That's right. The `else` block *unconditionally* executes after the `for` 
block. The only way to skip it is to use `break`, which skips all the way 
out of the combined for...else statement.

This is a very useful feature, very badly named.



-- 
Steven



More information about the Python-list mailing list