6. is_prime



Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.

it should return False. because when n iterates through the range. 9 % 3 == 0, which should return False. Idk why it is returning True!!

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


a function ends the moment a return keyword is reached

if a return keyword is reached in a loop, the loop will break. So your loop breaks in its first iteration


so how do I prevent this/fix this??


place return True outside the loop


Thank you! It works now. But I still do not understand the logic behind this. I understand that once it hits return, it will end. But for example, if you input 9, wouldn't it be divisible by 3 thus returning False and thus ending the loop?


yes, but the first number checked is 2, so 9%2==0 is false, so true will be returned (the loop will break), because you have if/else, in the first iteration the loop will break (either true or false), with for/else else will run when loop conditions becomes false. When a number is not a prime number, false will be returned


ohhh okay that makes sense. thank you!


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