mistake in python tutorial

Dave Angel d at davea.name
Tue Jun 5 22:00:55 EDT 2012


On 06/05/2012 09:43 PM, Miriam Gomez Rios wrote:
> Hello, I think that the example in section 4.4 in the tutorial for python 2.7X is wrong.
>
> http://docs.python.org/tutorial/controlflow.html
>
>
>
> It will end up printing this if you run the exact code listed in the tutorial.
>
>
>
> 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
>
>
>
> I believe it is because the is no break in " else print n is a prime number" and
>
> it never prints anything about number 2 because the second for is like range(2,2)
>
> which is empty so it does nothing.
>
>

Hate to tell you, but the example works as it exists on the website.  If
you got your output, you must have messed up the indentation, which is
VERY important in python.

In particular, the else clause has to line up with the for statement,
NOT with the if statement.

If it helps, this is the correct indentation.  Paste it into a file, and
run it.

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'

-- 
DaveA




More information about the Python-list mailing list