Is_prime failed on 9


#1



Can Someone help me why this failed on 9?


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
    else:    
        for n in range(2, x):
            if x % n == 0:
                return False
            else:
                return True


#2

You could add prints to see if it's doing the steps it's supposed to be doing


#3

Did you loop at similar topics? There are many of this topics on the forum.

A function ends the moment a return keyword is reached, this currently happens in the first iteration of your loop because there are two possible scenarios:
if is true, false is returned
else will run because true is false, true will be returned

but you don't want to return true at the first iteration of the loop, you only want to return true after the for loop has finished running


#4

I just got the same error and figured out what the problem is. The problem is with the indentation in the last "else." It should be indented in line with "for n in range(2, x)" instead.


#5

thank you for your advice, I get it now


#6

thank you, it is really inspiring for the iteration explain


#7

yep, thank you, I get it finally


#8