6. is_prime


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


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


#2

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


#3

so how do I prevent this/fix this??


#4

place return True outside the loop


#5

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?


#6

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


#7

ohhh okay that makes sense. thank you!


#8

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