Please help with 15.6!


#1



This is the excercise I am stuck at...:
https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096


This is the error I get from my code:

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


I thinks the problem is that my function only checks for the first n it gets. The function gives the right outcome for the prime number 5, I think because the first n(5 % 2 == 1) does not equal 0 (and so returns false) and coincidentally all other n's don't equal 0 as well. When my function reaches 9 the first n gives (9 % 2 == 1) so it returns false, it doesn't check for other n's but 9 % 3 == 0. I am not sure if this is the problem but I have no idea how I can check if this is the case, and/or how I solve this.

Thanks in advance!


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


#2

well, you are right. The reason only the first value is tested (by loop) is because return will end the function

so, we only want to return True after the function has finished running (x is then not divisible by n, so the number is a prime number)


#3

Thanks for the response! It is still not clear to me how I keep looping over n instead of returning it. What code do I need to write in order to get that loop going?


#4

not reaching a return keyword.

the moment a return keyword is reached, the function ends immediately (even when the return keyword is reached in a loop, the loop just breaks so the function can end)


#5

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