6. its_prime


I have no idea why it fails on is_prime(9), and returns true instead of false. I’ve followed the logic of it when it’s 9 and I thought the 9 % 3 would be tested as each iteration goes up 1 so it should be false…I tried messing with the range but that created other numbers that didn’t work and it seems right already in my mind (it’s what the the exercise tells me to do)…I’m stumped

def is_prime(x):
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
        for n in range(2, x - 1):
            if x % n == 0:
                return False
                return True


get rid of the -1 in for n in range (2, x-1) range stops at the integer before the 2nd parameter
so range (2,9-1) gives you 2,3,4,5,6,7

also as far as the issue with 9 you aren’t actually looping the whole thing
you return true or false off of x % 2 every time so it stops there. the only reason it didn’t fail before 9 is 9 is the first odd non-prime.
You need to bring the return True outside of the loop


Found the problem, its my indentation. The else: return true should be in line with the FOR and not the IF…Don’t quite know why so if somebody could explain that…I did a similar mistake in the factorial one but I had an if statement before the for loop and was told it would execute it being true on the first iteration, but I don’t think it would be doing it here because the order is different.


I would like an explanation for that as well…


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