Is_prime help



Can someone please look over my code. I get the correct responses but it tells me to switch to the opposite answer.

def is_prime(x):
    for n in range(int(x-1)):
        if x < 2:
            return False # not prime
        elif x % 2 == 0: # no remainders making it even
            return False # not prime
        return True

print is_prime(0)

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

Thank you very much.


0 is not a prime number, so false should be returned. As you can see, your code returns true

the problem is that for x=0 you get the following loop condition:

for n in range(int(0 - 1))

so the start value (default, 0) to stop value (-1) evaluate to false, so else: return True runs, which shouldn't happen.

Maybe you should move your if condition to before the loop?


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