Is_prime--why is it giving me "none" error?


#1

I'm not sure why my code is not working.

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

It's giving an error called "Oops, try again. Your function fails on is_prime(3). It returns None when it should return True."

I've tried this dozens of times with different conditions, but it always fails whenever I modify the code.


#2

When x is 3 this loop does not run. Since there is no other return statement, Python has nothing to return so the caller sees, None.

Slide these lines over to the left to close out the outer if statement. Then the elif x==2 line can be removed. Setting the range to begin on 2 elliminates even numbers right off the bat.

if x < 2:

if x > 2:
    for n in range(2, x):

else:
    return True

#3

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