6/15 is_prime [Solved]



It keeps giving me the error: Oops, try again. Your function fails on is_prime(0). It returns None when it should return False.

I would think that the code would work and correctly return False. But it doesn't do that. I have no idea what's wrong with it.

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

print is_prime(0)


lets take a look at your loop:

for n in range(2, -1):

uhm.. the steps are +1 by default, so no steps are taken. I would write special cases for the low numbers (0,1,2,3) (i see you have, put it outside the for loop)

One more thing. a function ends the moment a return key word is reached, which in your case happens in the first run of the loop. You might want to re-indent your else statement, so the entire loop can run

Is prime

I'm still not really understanding how to complete this part.

EDIT: I'm trying again to fix this for myself instead of relying on others, and now the error is gone. But i'm getting a new one. Now it says that the function fails for is_prime(2) as it returns None instead of returning True.

EDIT 2: I've tested it with a few values to see exactly which ones are not working correctly. The only two that I can find that aren't working correctly are is_prime(2) and is_prime(3)

EDIT 3: I've managed to fix those two errors, but now I have another one. is_prime(9) is returning True when it should be returning False


Very good you almost fixed it :slight_smile: Do you understand why?

yep, it will fail on is_prime(9) as i explained here:


Just wanted to say thank you. I much prefer the responses that hint at solutions rather than just providing lines of code without explanation. I was stuck on this one for a few hours and was able to finally figure it out with help from you both. Thanks again


3 posts were split to a new topic: Is prime