Problems with is_prime


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6


"Your function fails on is_prime(9). It returns True when it should return False."


I don't get why it doesn't return False at 9 instead of at other numbers. If anyone could take a look at my code and let me know that would be great :slight_smile:


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

You are overthinking this. Try following this template:

def FUNCTION(PARAMETER):
    if PARAMETER < 2:
        return BOOLEAN
    elif PARAMETER >= 2:
        for EACH in range(2, PARAMETER - 1):
            if PARAMETER % EACH == 0:
                return BOOLEAN
        else:
            return BOOLEAN

Make sure not to just follow the template and move on. I want to make sure that you understand how and why this works. If you have any questions, just ask.


#3

Okay, that worked, thanks for the quick answer! I mostly get the solution, I'm just confused why my solution didn't work as it seems mostly the same.

For the record, I did range (2, x) instead of x-1 since range (2,x) includes all numbers from 2 to x-1 anyways.


#4

Actually the issue with mine was just the indentation. If I bring the else in line with the for then my code works just fine. Still weird to me, because you'd think the if should be in line with the else


#5

That is correct. The reason why the else statement should not be within the for loop is quite simple; We want the else statement to catch everything else that hasn't met one of our previous conditions. Therefore, it should be inline with the original if/elif statements. This way, if someone enters anything that is not a prime integer, the function will return false.


#6

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