"Weird" Indentation? (Or: is there a for...else construct?)
Peter Otten
__peter__ at web.de
Sat Feb 7 09:32:54 EST 2009
Andreas Waldenburger wrote:
> I've found something in the spirit of the following (in the epydoc
> sources, if you care):
>
> if True:
> print "outer if"
> for t in range(2):
> if True:
> print "for if"
> else:
> print "phantom else"
>
> For the life of me I can't place the "else". Which if clause does it
> belong to? None, it would seem from running the above snippet:
>
> outer if
> For if
> For if
> Phantom else
>
> It seems that there is a for...else construct. Replacing the inner if
> with pass seems to confirm this. The else clause is still executed.
>
> What's broken here: Python or my brain?
Your rtfm sensor?
http://docs.python.org/reference/compound_stmts.html#the-for-statement
In short, the else suite is executed unless the for-loop is left
via 'break':
>>> for i in [1]:
... break
... else:
... print "else"
...
>>> for i in [1]:
... pass
... else:
... print "else"
...
else
>>>
Peter
More information about the Python-list
mailing list