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

There always something wrong: "Oops, try again. Your function fails on is_prime(3). It returns None when it should return True."
Can anyone help me with that? Thanks!



after your for loop, you should return True.

All numbers which survive the loop are prime numbers, for those number true should be returned.


I follow your interesting proposition (see below) and my function fails on 9 and send me a True on the command
Because 9 is not a prime number :
So I ask myself and I can't understand why it doesn't work. Is somebody understand what's happening ?

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
        for i in range (2, x):
            if x % i == 0:
                return False
                return True


a function ends the moment a return keyword is reached, currently that happens in the first itertion of your loop. lets walk over the loop like the program would:
well, we clearly reach the for loop. so then we have:

for i in range (2, 9):

lets look at the if condition:

if 9 % 2 == 0:

this is false, so now else will execute. Oh hold on, we only want to return true after the loop has finished running

change the indent of else so that else only runs after the loop has finished running


That's excellent : it works after a long time of research, thanks a lot!


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