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

I do not understand why it is not working for x=9.Please help.

def is_prime(x):
    if x>2:
        for item in range(2,x):
            if x%item==0:
                return False
                return True
    elif x<2:
        return False
        return True


the first value tested by the loop for x=9, is 2, agree? so then we get:

if 9%2==0:

which is false. So, else will run. Which means a return keyword is reached

the moment a return keyword is reached, a function ends. This means, the loop has to break

Is this the desired behavior of your program?


Thank you for the reply. How should I correct my code?


i actually left that for you to figure out, based on my explanation, what is the problem and how do you think you can solve it? Please tell me, so i can fill in any missing gaps

  1. The for loop should check remainder function for every number 2,3,4,5.....x-1.
  2. For the first encounter where input%x==0, the function should return False. This would mean there is one more number other than 1 and the input number itself, by which the input number is evenly divisible. Hence the input number is not prime.
  3. By checking x%item==0 inside a for loop, I assumed it will check for every value between 'Range(2,x).

This is how I would solve the problem.


but as i just try to explain, this doesn't happen?

Your loop finishes in its first iteration because a return keyword is reached. Which causes the function to end. (in order for the function end, the loop needs to break)

So what would be the solution to prevent return True from being reached to early?


Hi Stetim94,

The solution to prevent return True being reached so early is to place the return statement outside the loop.


I can use a counter (initially set to 0) wherein the counter gets incremented to 1 each time a number in range(2,x) is a divisor of the input number. So at the end if counter>0, input number is not prime.


this sounds like the good solution :slight_smile: try to implement it. That should solve the problem :slight_smile:


Hi Stetim94,

Thank you helping me figure this out :grin: