6/15 is_prime


#1

This is my code:

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

When I run this code it brings up the following error:
Your function fails on is_prime(2). It returns None when it should return True.

I have fiddled with the code for a while now and it doesn't seem to work at all. Can anyone help?


#2

there are two problems, i would include 2 on this line:

    if x < 2:
        return False

now it checks for numbers smaller then 2 (not 2), you can resolve this issue by using <=, which means smaller or equal to 2.

The second problem is that your for loop only runs once, either you if statement is true otherwise your else statement will be executed, either way, there is a return statement already in the first run of the loop, the moment return is reached, the functions ends (so does the loop in the function). The else statement should be on the same indent level as the for loop (this way, the loop will run until it finished all numbers), if nothing is returned in the for loop, else will get executed, and return something