6. is_prime


def is_prime(x):
if x < 2 or x == 0:
return False
elif x == 2:
return True
for i in range(2,x-1):
if x%2 == 0:
return True
return False
can someone help me to fix my code please.
error message:Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.


It is sufficient to check if x is less than 2. Zero will be in the set so we needn't test for it.

As for the test of 2, we can do that implicitly by excluding it from the loop.

if x > 2:
    for ...

Values less than 2 are immediately rejected, and values greater than 2 are allowed into the loop. That leaves 2 all by itself so at the end of the program we simply return True.

Consider also that the if statement in the loop does not need (rather should not have) an else clause. Just the if with a return of False. Now when the loop has fully completed, any values remaining will be prime so they will drop down to the last line and return True, as well as the 2.


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