Problems with is_prime


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


You are overthinking this. Try following this template:

    if PARAMETER < 2:
        return BOOLEAN
    elif PARAMETER >= 2:
        for EACH in range(2, PARAMETER - 1):
            if PARAMETER % EACH == 0:
                return BOOLEAN
            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.


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.


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


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.


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