6. Is_Prime


#1

My function is failing on 9 and so on.
I'm guessing that my loop is not functioning correctly, as in it only checks if it evenly divides for 2 and then stops.

Is this what is happening? and how can I fix my loop to check all for all the numbers in the range?

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


#2

this is because a function ends the moment a return keyword is reached, so you only want to return True after the for loop has finished running


#3

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