Repeat an exception

Stephen Hansen apt.shansen at gmail.com
Thu Feb 4 11:38:37 EST 2010


On Thu, Feb 4, 2010 at 4:59 AM, Jean-Michel Pichavant <
jeanmichel at sequans.com> wrote:

> What the hell is this 'for else' loop !! :D First time I see this statement
> for years.
> I'd never thought I'd still learn something that basic.
>

Its one of the least used constructs in Python, I think, and leads to
periodic statements like this on the list where people who think they know
all about Python suddenly see it and go WTF :)

But in Python, all loops have an "else" clause that is fired when the loop
terminates-- but *only* if it terminates normally, where 'normally' is
basically, 'if you don't use break to exit the loop prematurely'.

It allows you to do certain things in a way which is (arguably, and I so
don't want to start an argument about this) a bit cleaner, where the normal
method would require a flag or some such. For example, if you need want to
loop over a sequence to test to see if they all match some criteria, you can
use a for..else, or some flag variable.


--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100204/11224df8/attachment-0001.html>


More information about the Python-list mailing list