Is_prime


#1

Somehow this code stucks by 9. The error code is "Oops, try again.
Your function fails on is_prime(9). It returns True when it should return False."

Here is my code:

def is_prime(x):

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

#2

The reason it's returning true is because of your if/else statement in your for loop. The for loop is set to go through a range and starts with 2. 9 % 2 does not equal 0 so the else statement is ran which returns True and exits the loop. If you remove that else statement then the for loop with continue to evaluate other number in the range until it returns False or runs out of numbers. This also means that you need to change the very bottom else so that it returns True.


#3

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