[Tutor] Possible error on 2.1b1

D-Man dsh8290@rit.edu
Tue, 13 Mar 2001 18:34:34 -0500


On Tue, Mar 13, 2001 at 04:52:51PM -0300, Blitz wrote:
| Hi, I have tried this example from the Tutorial and I get different
| results.  This is from the tutorial:
| 
| >>> for n in range(2, 10):
|      ...     for x in range(2, n):
|      ...         if n % x == 0:
|      ...            print n, 'equals', x, '*', n/x
|      ...            break
|      ...     else:
          ^^^^^
Note the indentation level.

| This is my code, the same statements from the tutorial, but different
| results:
| 
| Python 2.1b1 (#11, Mar  2 2001, 11:23:29) [MSC 32 bit (Intel)] on win32
| Type "copyright", "credits" or "license" for more information.
| IDLE 0.6 -- press F1 for help
| >>> for n in range(2, 10):
| 	for x in range(2, n):
| 		if n % x == 0:
| 			print n, 'equals', x, '*', n/x
| 			break
| 		else:
        ^^^^^^^^
Note this indentation level.

| 			print n, 'is a prime number'
| 
| 			
| 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
| 
| Do you know why this happens? Note that I used Python 2.1b1 for Windows.

Your "print n is a prime number" statement is inside the loop that
checks for a divisor.  Thus, every time a particular divisor fails,
you print "n is a prime number" rather than waiting until after all
potential divisors have been tried.  The "else" on a "for" statement
is a bit weird, but read the docs closely as to its semantics and try
to see why it is useful here.  I must admit that I am not very
familiar/comfortable with "else" clauses on loops, but that is largely
because no other language that I know supports such a construct.

-D