6/15 is_prime


#1


What exactly is wrong with my code? It says " 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 
    for n in range(2,x):
        if x%n == 0:
            return False
        else:
            return True


#2

Hi, @kaitod ,

Using the case where x is equal to 9 as an example, consider how the execution of your code proceeds. What happens in the if structure during the first iteration of the for loop, when n is equal to 2?


#3

Same problem here too
def is_prime(x):
if x<2:
return False
elif x==2:
return True
n =2
while n>=2 and n<=x-1:
print n
if x%n==0:
return False
break
else:
return True
n = n+1


#4

Yes, like appylpye said, the problem in your code is situated in your for loop. Try to use backspace 4 times on your else statement so you get a for&else loop. Good luck :slight_smile:


#5

@kaitod ,

See @krec01's response.

If you remove one level of indentation from the else block, it will become directly associated with the for loop rather than with the if block, and that will resolve the issue. The for loop will then be able to complete all its iterations, unless we discover a divisor for x. If a divisor is found, we do not have a prime number, and False is returned. On the other hand, if no divisor is found, the for loop will complete all its iterations, and we do have a prime number. In that case, the else block will execute, returning True


#7

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