Is_prime help


Stuck on the is_prime exercise. Really have no idea why the code isn't working, would very much appreciate any guidance.

Error message is: Your function fails on is_prime(9). It returns True when it should return False.

I don't know why 9 returns true—as far as I can tell it should break when 9%3 == 0 and returns False. Does this mean there is a problem with my understanding of range? Or something completely different? XD

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


for 9, the first number the loop will test is 2, agree?

so 9 % 2 == 0, will evaluate to false, so else will execute, which returns true. The function ends (a return keyword is reached), so the loop simply breaks


Thank you! That was really helpful! Figured it out now :slight_smile: Will a loop always break when a return keyword is reached, or just this exercise? (Sorry if that's a silly question!)


By default, a function returns None at the end, we can use the return keyword to make the function return something else/different. A function always ends when a return keyword is reached, so the loop always breaks


i got the same problem but wondering how to solve it.

could u enlighten me?

*1 min later
forget about it :expressionless: i just had to move the else out of the "if" and into the "for" loop


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