[Tutor] else clauses on loops

Norvell Spearman norvell@houseofspearman.org
Thu Jul 31 13:20:03 2003


I'm working through the Tutorial yet again (Release 2.3 this time) and
this time got stuck on section 4.4, ``break and continue Statements, and
else Clauses on Loops.''  Here's the code from that section:

    >>> 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'
    ...
    2 is a prime number
    3 is a prime number
    4 equals 2 * 2
    5 is a prime number
    6 equals 2 * 3
    7 is a prime number
    8 equals 2 * 4
    9 equals 3 * 3

With which for loop is the else associated?  Because of the indentation
level I'd think it belongs to the outer for loop, but the else gets
executed when the loop is not terminated by a break or continue.  In
this case the break belongs to the inner for (right?) so how does else
know that it's supposed to execute?

-- 
Norvell Spearman