[Tutor] else clauses on loops

Jeff Shannon jeff@ccvcorp.com
Thu Jul 31 13:44:01 2003


Norvell Spearman wrote:

>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'
>    ...
>
>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?
>

It uses the same format as an if/else -- the else should be at the same 
indentation level as the condition statement that it applies to.  With this:

if test1():
    if test2():
        foo()
    else:
        bar()

it's expected that the else applies to the test2() condition, because 
they are at the same indentation level.  If the else were to apply to 
the test1() condition, it'd be indented like so:

if test1():
    if test2():
        foo()
else:
    bar()

The same logic holds true when it's for statements instead of if 
statements -- any time you have statements that are a syntactic group, 
they should be at the same indentation level.

Jeff Shannon
Technician/Programmer
Credit International