Nested for loop problem

Michael Geary Mike at DeleteThis.Geary.com
Sat Nov 8 18:43:08 EST 2003


> #!/usr/bin/python
>
> 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'

> I have another question which I hope you can answer. If I do
>
> 2 % 2 in the python interpreter, the answer is 0, and yet 2 is
> a prime number.

2 modulo 2 is zero. Any number modulo itself is zero.

If the question is why the code above reports 2 as a prime number, that's
because it never gets to the "if n %x == 0" when n is 2. "for x in
range(2,2)" does not execute the loop at all but goes directly to the else.

I think you would find it helpful to step through this code line by line in
any Python debugger such as PythonWin or IDLE--that way you can see exactly
what it does as it executes.

-Mike








More information about the Python-list mailing list