Newbie question: Explain this behavior

David Smith ac063 at lafn.org
Fri Jul 15 00:46:40 CEST 2005


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'


Output:

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



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

Output:

3 is a prime number
4 equals 2 * 2
5 is a prime number
5 is a prime number
5 is a prime number
6 equals 2 * 3
7 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number
8 equals 2 * 4
9 is a prime number
9 equals 3 * 3




More information about the Python-list mailing list