Most of the other answers have given an explanation for how to correct your code. However, since we're on the topic of primes, I wanted to give my alternative solution.
Instead of checking all the numbers from 2 to n
, you only have to check from 2 to the square root of n
(n**0.5
). This is because any factor of n
greater than n**0.5
must be paired with a factor less than n**0.5
.
def prime(n):
n = int(n)
assert n > 0, "n must be a positive integer."
assert n != 1, "1 is neither prime nor composite."
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
I just tested this by getting every prime number between 1 and 100:
>>> primes = [i for i in range(2, 100) if prime(i)]
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]