Is_prime help


#1


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
    else:
        for n in range(2,x):    
            if x%n == 0:
                return False
                break
            else:
                return True


#2

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


#3

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!)


#4

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


#5

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


#6

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