[Python-ideas] for/else syntax
Gerald Britton
gerald.britton at gmail.com
Sat Oct 3 17:34:21 CEST 2009
Yes, you need to have some early exit in the body of the loop.
Anyway, it's just a toy example. Not too hard to come with better
ones.
On Sat, Oct 3, 2009 at 11:31 AM, Masklinn <masklinn at masklinn.net> wrote:
> On 3 Oct 2009, at 13:49 , Gerald Britton wrote:
>>
>> Sory Carl, I did NOT get it dead wrong. The else is executed if the
>> for loop falls through. That's the whole idea. Probably I should
>> have set i to -1 in the else clause of the toy example though:
>>
>> for i, j in enumerate(something):
>> # do something
>> i += 1
>> else:
>> i = -1
>>
>> if i > 0:
>> # we did something
>>
>> If you don't think the else is executed when the for-loop falls
>> through, then you should re-read the documentation, here:
>
> Carl didn't dispute that point. In fact that's exactly the issue with your
> code: since you don't have any `break` statement in your `for:` loop, the
> `else:` clause will *always* be executed, whether `something` is an empty
> collection or not.
>
> Thus, the following `if i > 0:` clause cannot under any circumstance be
> executed.
>
> Your code (unless there is a break in the 'do something' part) is equivalent
> to:
>
> for i, j in enumerate(something):
> # do something
> i += 1
> i = -1
>
> if i > 0:
> # can never happen
>
--
Gerald Britton
More information about the Python-ideas
mailing list