Kinda newb-ish question

Mark Dufour m.dufour at student.tudelft.nl
Thu Dec 11 21:57:45 EST 2003


On Friday 12 December 2003 01:50, ChocoboMog123 wrote:
> What's wrong with line 8 in this code?
> x=1
> while 1==1:
>     x=x+1
>     y=range(1,x)
>     z=0
>     q=9
>     for count in y:
>         q=x%y
>         if q==0:
>             z=z+1
>     if z<1:
>         print x
> It keeps giving me
> Traceback (most recent call last):
>   File "C:\Python23\Prime Number.py", line 8, in -toplevel-
>     q=x%y
> TypeError: unsupported operand type(s) for %: 'int' and 'list'
>
> It's supposed to be a program to print out prime numbers.
> If anyone knows of a program that does this or can write one, can you
> show me the code? Thanks.

Sure. The expression range(1,x) produces a list, not a number. So y is a list, 
and x%y now tries to perform a modulo operation with a list as modulo number!

Instead of using z, you might also use a boolean, or True/False variable, 
perhaps like this:  

x=1

while 1:
    x += 1
    prime = True
    for y in range(2,x):
        if x%y == 0:
            prime = False
            break
    if prime: print x

Notice the (2,x) instead of (1,x). You don't want to test for division by 1.. 

Of course, finding primes this way by trial division is a very slow method..  
A simple optimization would be to only try numbers up to the square root of 
x. 


Mark Dufour.
-- 
"The employment agency has selected an immature and unproven software package 
and its functionality is at the best close to Office 97," said Microsoft 
representatives.






More information about the Python-list mailing list