"for" with "else"?
Mark Jackson
mjackson at alumni.caltech.edu
Thu Sep 25 09:52:04 EDT 2003
Invalid User <user at invalid.domain> writes:
> Is this to be expected?
> (python 2.2.2)
>
> ++++++++++++++++++++++++++++++=
> >>> for x in range(5):
> .... print x*x
> .... else:
> .... print "done"
> ....
> 0
> 1
> 4
> 9
> 16
> done
> ++++++++++++++++++++++++++++++=
Yes. The else clause is invoked iff the for loop terminates normally.
Contrast with:
++++++++++++++++++++++++++++++
>>> for x in range(5):
... print x*x
... if x==4:
... break
... else:
... print "did all"
...
0
1
4
9
16
>>>
++++++++++++++++++++++++++++++
(This happens to be the *reverse* of what my intuition expects - it
would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and
one must simply remember it.)
--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
There are no foolish questions and no man becomes a fool
until he has stopped asking questions.
- Charles P. Steinmetz
More information about the Python-list
mailing list