Is_prime: function fails on is_prime(3)


My error message is: Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.

I don't understand why it doesn't work. Please help me.

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True

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


why subtract one from x? range() doesn't include its stop value (its values lesser then (<) stop value, not lesser then or equal to (<=)), so i don't see a reason to subtract one


Now I have just replaced x - 1 with x and it still doesn't work. In the error is now 9 instead of 3.


a function ends the momnet a return keyword is reached

if a return keyword is reached in a loop, the loop will break

so your loop always breaks in your first iteration (For both prime and not prime numbers), is this the desired behavior?


No, I need it to go through the whole code


if the number is a prime number, the whole loop should run, when the loop has finished running (this only happens if false is not returned), true should be returned

so what should we do to overcome this problem?


Print statements go a long way to finding out where the program behaves differently from what you intended


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