# is_prime function fails on 9

#1

Hello everyone! I am having trouble with this code. It returns an error when I run it: "Your function fails on is_prime(9). It returns True when it should return False." Thanks for your help!

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

#2

The problem you have here is that the loop only execute once. assuming x = 9:

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

now, if x%n (9%2) == 0 is false, so it goes to the else statement, and returns true. The loop ends. What you need to do, is to put return True on the same line as the for loop, this way the for loop execute for all number in range, and if none of the triggers the if statement, it will return True (meaning the number is prime), the result code:

``````for n in range(2, x):
if (x%n) == 0:
return False
return True``````

#3

I understand why it originally failed now. However, I am still getting the same error message.

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

#4

My mistake, you don't need else now, and i see i screwed up. it should be:

``````for n in range(2, x):
if (x%n) == 0:
return False
return True``````

this way, the loops ends the moment the if statement is true (and you return false), or after the range is done, then it returns True.