Help with is_prime


I cannot figure out what is wrong with the code?
This is the error message that I keep getting (with different numbers):

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

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


Remove the else and set the return statement to match the indent of for.


Why don't you need the two lines? My codes was similar to this and your solution worked for mine as well


if ...:


When the loop is inside the if branch it will not see the code in the else branch, only the values that fail the if condition will. The return from the loop will be None.

if x < 2: return False

for n in range(2, x):
    if x % n == 0: return False

return True

When there is no return inside the loop, it runs to completion and flow drops to the last line.


Okay, got it , thankss!!


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