[Python-ideas] for/else syntax
Gerald Britton
gerald.britton at gmail.com
Sat Oct 3 17:32:33 CEST 2009
Yes, quite right. Another way would be:
for i, j in enumerate(x):
# do something
i += 1
else:
if "i" not in vars():
i = 0
Is it better than initializing before? Not sure. I guess it's a
matter of taste.
On Sat, Oct 3, 2009 at 11:22 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 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:
>>
>> http://docs.python.org/reference/compound_stmts.html#the-for-statement
>>
>> Where it says (just as I did, but in other words):
>>
>> "When the items are exhausted (which is immediately when the sequence
>> is empty), the suite in the else clause, if present, is executed, and
>> the loop terminates."
>
> The code in your example is semantically identical to the following:
>
> for i, j in enumerate(something):
> # do something
> i += 1
> i = -1
>
> if i > 0:
> # This block is unreachable...
>
> Without a break statement in the body of the loop the else will by
> executed unconditionally, hence it is exactly the same as if the code it
> contains was just inline after the loop body.
>
> The semantics you describe can be obtained only by initialising i before
> the loop:
>
> i = -1
> for i, j in enumerate(something):
> # do something
> i += 1
>
> if i >= 0:
> # We did something
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
> ---------------------------------------------------------------
>
--
Gerald Britton
More information about the Python-ideas
mailing list