Your x % number not in listrange
is going to be true a lot of the time, even for prime numbers. It is the wrong thing to test for prime numbers.
Say you start with 7
, a prime number. The first number to be tested is 2
:
>>> x = 7
>>> number = 2
>>> x % number
1
So the remainder is 1
. 1
is not in the listrange()
values (which go from 2
through to 6
, inclusive). That's because for any given prime number larger than 2, division by 2 will always result in 1
as the remainder, and 1
is never in your list.
2
is not the only such value for which the remainder of the division is 1. For the prime number 7919, there are 7 such numbers:
>>> [i for i in range(2, 7919) if 7919 % i < 2]
[2, 37, 74, 107, 214, 3959, 7918]
so your code will print Prime number 7 times. And the test would be true for non-prime numbers too; 9
is not a prime number, but 9 % 2
is 1
too, so your code would claim 9
to be a prime number. For 1000
, not a prime number, your code would print Prime number 32 times!
You can't state that a number is a prime number until you have tested all the values in listrange()
and have determined that none of those numbers can divide the number without a remainder. So you need to test after you loop; you could test if emptylist
is empty; that means there were no divisors, the very definition of a prime number:
for number in listrange:
if x % number == 0:
emptylist.append(number)
if not emptylist:
print ("Prime number")
As a side note: you don't need to turn a range object into a list of numbers, not only does testing if number in range(...):
work, it's a lot faster than using the same test on a list.