15/6 is_prime failiure. What am I missing?


Exercise 15/6

I've tried various ways of messing with the code, but it keeps giving me 'Oops, try again. Your function fails on is_prime(0). It returns None when it should return False.', sometimes with it suceeding at is_prime(0), but failing at is_prime(1) or (9).

By what I understand, this should return True for is_prime(0), but it still gives the same error.

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

I'm sure the solution I'm missing is very simple, but I can't get it. Thank you for your help.


Move this to the left four spaces so the else lines up with for.


That gave me this error:
Oops, try again. Your function fails on is_prime(0). It returns True when it should return False.
But thank you!


One fix would be to set an opening condition to check for < 2 and return false.


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

I have edited the code a bit. It should work if 2 is passed as an argument. Thanks for pointing it out @codeninja84962!


I had to change it to x < 2, but this worked! Thank you.


Neither x<=2 nor x <2 with this code below should work:

As it's ignoring 2 as a prime number. x % n == 0 . Can you explain guys? I did it different way which count 2 as prime.


The reason that the code (corrected with x<2 instead of x<=2) doesn't end up calling 2 a non prime number is that the range used in the for loop ends up being an empty list in that case, making it never enter the body.


Thanks for your explanation.