6.is_prime


#1

def is_prime(x):
    if x < 2 :
        return False
    elif x ==2:
        return True
    else:
        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!

`


#2

after your for loop, you should return True.

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


#3

I follow your interesting proposition (see below) and my function fails on 9 and send me a True on the command
is_prime(9)
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
    else:
        for i in range (2, x):
            if x % i == 0:
                return False
            else:
                return True

#4

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


#5

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


#6

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