Noob: Loops and the 'else' construct

Diez B. Roggisch deets at nospam.web.de
Sat Oct 20 12:52:29 EDT 2007


MRAB schrieb:
> On Oct 19, 4:11 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <parnel... at comcast.net>
>> escribió:
>>
>>> I have just come across a site that discusses Python's 'for' and
>>> 'while' loops as having an (optional) 'else' structure.
>>> At first glance I interpreted it as being a bit like the 'default'
>>> structure in PHP's switch block... But the switch block isn't a loop,
>>> so, I am now confused as to the reason for using 'else' with the for
>>> and while loops...
>>> A few quick tests basically show that statements in the else structure
>>> are executed at the fulfillment of the loop's expression (ie, no
>>> break).
>> A `while` loop tests a condition: if it evaluates to true, keep cycling;
>> if it is false, stop. The `else` clause is executed when the condition is
>> false, as in any `if` statement. If you exit the loop by using `break`,
>> the `else` part is not executed (because you didn't get out of the loop by
>> determining the condition falseness)
>>
>> You can think of a `for` loop as meaning `while there are remaining
>> elements to be iterated, keep cycling` and the `else` clause applies when
>> there are no more elements. A `break` statement does not trigger the else
>> clause because the iteration was not exhausted.
>>
>> Once you get the idea, it's very simple.
>>
> It's useful when you want to search for an item and to do something if
> you don't find it, eg:
> 
> for i in items:
>     if is_wanted(i):
>         print "Found it"
>         break
> else:
>     print "Didn't find ir"

Wrong. It's not:

for i in []:
     print i
else:
     print "I'm reached, too"

prints out "I'm reached, too"

The else will ONLY not get executed when the loop is left prematurely 
through a break:

for i in [1]:
     print i
     break
else:
     print "I'm reached, too"

won't print the "I'm ..."


Diez



More information about the Python-list mailing list