Is_prime(9) returns true when it should return false


#1




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


I don't understand why it doesn't work, it looks correct


Replace this line with your code. 
def is_prime(x):
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
    else:
        for n in range(2, x-1):
            if x % n != 0:
                return True
                break
            else:
                return False


#2

a function ends the moment a return keywod is reached, this currently happens in the first iteration of the loop.

You only want to return True after the for loop has finished running


#3

I tried modifying the code and creating a variable pr but it now fails on 6

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


#4

I also tried specifying that 6 is false and it returns true for 9 again.
Could someone just give me a working code so that I can reverse engineer it?


#5

a return keyword is still reached in the iteration of the loop, change the indent of else so return True is outside the for loop


#6

This is my function is_prime, the key is to check is the number has more than 2 dividers, it it has means that the number it is not prime, therefore I use a variable named count equal to zero at the very beginning of my funcion then I check if the number is divisible by n ( x % n == 0) and if it is I add one to that count variable that's the key.

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


#7

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