Is_prime : What's wrong?


#1

In is_prime, the following error appears.

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

What's wrong with my code?

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

Sorry, I'm not good at English.


#2

here:

for n in range(2, x-1) :

why do x-1? range() does not includes its stop value, so you don't have to subtract one

Aslo, a function ends the moment a return keyword is reached

So, your function ends in the first run/iteration of the loop.

But a number is only a prime number if the whole loop finishes running (x is not divisble by n), so you should place return True outside the loop


#3

Thank you, I got it !


#4