What is wrong with my code for is_prime?


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

#2

let's say i have 9 (which is not a prime number), so elif (elif x >= 2) is true, then we have the for loop, so x is 9, and n is 2, so 9 % 2 == 0 is not true, so else will execute, return True. When return is reached, the function (which include the loop ends), you might not to want use else, i think about where you place you return True.

You can very nicely that the loop only execute once if you add a print statement and call the function:

def is_prime(x):
     if x < 2:
         return False
     elif x >= 2:
         for n in range(2,x-1):
             print n, x
             if x % n == 0:
                 return False
             else:
                 return True
print is_prime(9)