If/then style question

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 17 09:38:11 EST 2010


On Fri, 17 Dec 2010 09:09:49 -0500, Rob Richardson wrote:


> First, just to clarify, I don't think the indentation I saw was what was
> originally posted.  The "else" must be indented to match the "if", and
> the two statements under "else" are in the else block.  The return
> statement is indented at the same level as the for statement, so that it
> will be executed after the for loop exits.  Correct?

I think that what you are missing is that for-loops can include an else 
clause too, like this:


>>> for x in (1,2,3):
...     print(x)
... else:
...     print("finished")
...
1
2
3
finished
>>>


The else block runs after the for block, unless you exit the entire block 
by returning, raising an exception, or using break:


>>> for x in (1,2,3):
...     print(x)
...     if x == 3: break
... else:
...     print("finished")
...
1
2
3
>>> 


Does that clear up what is going on?


-- 
Steven



More information about the Python-list mailing list