# Finding the bug!

#1

def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for n in range(2,x+1):
if x % n == 0:
print n
return False
else:
return True
WHAT IS THE PROBLEM IN THIS CODE???
ERROR MESSAGE:Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.

#2

A function ends the moment a return keyword is reached, so for `x=9` the first number tested by the loop is `n=2`, so that gives us the following if condition:

``if 9 % 2 == 0:``

this condition is false, so `else` runs, True is returned, the function ends

for a number to be a prime number, `x` must not be divisble by `n` so we only want to return True after the loop has finished running

#3

So in that case can we use the while loop?if yes then how can we use the while loop here.

#4

You can, but why would you? If you keep the `if/else` as it is, you get exactly the same error message with a while loop

so you want to place return True outside the loop

This way, if a number is not a prime number False will be returned which will end the function

If the number is a prime number, it gets succesfully through the loop, and then returns True

#6

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