Newbie question: Explain this behavior

Ross Wilson rzzzwilson at hotmail.com
Thu Jul 14 22:01:15 EDT 2005


On Thu, 14 Jul 2005 15:46:40 -0700, David Smith wrote:

> Why does code snippet one work correctly, but not two.  The only
> difference is the placement of the "else".  I know that indentation
> affects execution, but how does it change behavior in the following
> examples?  Thank you.
> 
> 1. for n in range(2, 10):
>        for x in range(2, n):
>           if n % x == 0:
>              print n, 'equals', x, '*', n/x
>              break
>        else:
>           # loop fell through without finding a factor
>              print n, 'is a prime number'
<snip>

A quote from "Python: Essential Reference (2/e)" (p56) says it best:

"The 'else' clause of a loop executes only if the loop runs to completion.
This either occurs immediately (if the loop wouldn't execute at all) or
after the last iteration.  On the other hand, if the loop is terminated
early using the 'break' statement, the 'else' clause is skipped."

Ross



More information about the Python-list mailing list