# Is_prime for some reason doesn't work on number 9

#1

Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.

I can see no reason why it would fail on 9. 3%9 should trigger return and end loop.

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

#2

Ok, so let us assume that `x = 9`, what happens in your code?

It starts with the `if`, but `9 < 2` is `False` so we go to the `elif`. `9 == 2` is `False` so we go to the `else`.

Now we have a `for` loop and the first value of `i` is `2`.

The condition of `if` is `9 % 2 == 0`, this is obviously `False`, but there is an `else` block, so we go there. And there is only a single statement - `return True` and this value will be returned.

In other words, your code will return `True` for every odd number that is `> 2`.

To solve this problem you can move `return True` outside the `for` loop.

6/15 is_prime : Working Fine. But not for 9 as a Prime Number
#5

``````def is_prime(x):
for n in xrange(2, x-1):
if x % n == 0:
return False
elif x < 2:
return False
return True

print is_prime(2056)
print is_prime(13)``````

Mine is outside the for loop and i still get this error
Oops, try again. Your function fails on is_prime(0). It returns True when it should return False.

#6

Different code, different problem.

Let us assume that `x = 0`. Your function starts with the `for` loop, but `xrange(2, -1`) does not yield any value so the loop will not be executed. So we are outside the loop and there is only one statement - `return True` and this value will be returned for `x = 0`.

You should check if `x < 2` before the loop.

#7

Thanks. After I fixed it, it runs smoothly now.

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

print is_prime(13)
print is_prime(2056)
print is_prime(0)``````

#8

You're welcome

#9

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