Is_prime using not equal in conditional statement

#1

So I eventually got the right answer by using "==" in if statement and switching boolean values at bottom. But I'm still curious as to why the code below doesn't work with "=!".

"You function fails on is_prime(2)" It returns "false" and should return "true"" is the error I'm getting. I've looked at some of the other posts on this problem but none that I've seen use != 0. I thought that made more sense since the function is called is_prime (hence you want to return a value of "true" when the argument is a prime number.

``````def is_prime(x):
if x < 2:
return False
elif x >= 2:
for n in range(2, x):
if x % n != 0:
return True
return False

print is_prime(7)``````

#2

Would this not be rather moot? We know already that x is not less than 2, so it must be the other... equal or greater.

This is a huge flaw. 15 % 2 is not zero, but 15 is not a Prime.

Think in opposite terms. Rather than eject the Primes, let them fall through. So your loop ejects non-primes (those that are divisible) as False, immediately, and ignores the others.

``````for n in range(2, x):
if x % n == 0: return False    # eject the non-Primes
return True                        # best candidate Primes fall through``````

Consider also that x = 2 does not even make it into the loop (range(2, 2) is empty, so no iterations) and skips around it.

#3

Since we're on the topic of is_prime, why do they indicate in the exercise that it should be:

``    for n in range(2, x-1):``

While I see you guys have written `for n in range(2, x):` instead?

I see that both solutions work out. But it seems x-1 causes problems with the nr 3, as 3-1=2 and range(2,2) would be empty? It doesn't cause any problems in the exercise, only in my head

#4

This question comes up a lot. I've chalked it up to the author intending it to be (2, x) since in range(), the upper bound is excluded so would equal to x - 1. It really doesn't matter though, since both will let 3 return as prime.

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.