Noob: Loops and the 'else' construct

Thorsten Kampe thorsten at thorstenkampe.de
Fri Oct 19 04:12:42 EDT 2007


* Gabriel Genellina (Fri, 19 Oct 2007 00:11:18 -0300)
> En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <parnell.s 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)

So a for/else loop is exactly the same thing as a for loop with the 
else clause outside the loop (except for "break")? Guess that's why I 
never used that...

Thorsten



More information about the Python-list mailing list