Is_prime: can someone explain to me why this code doesn't work for is_prime(9)?


#1



Hi all, I'm working through the is_prime exercise in the python module. I'm confused as to why this code isn't working when calling is_prime(9). The error I'm getting says the code is returning 'True' instead of 'False'. I've followed it through from start to finish, and I can't for the life understand why it would return 'True'.

I've added comments as I went through, specifically to track what was happening with '9' as the argument. I'm at a loss here folks and it's very frustrating!


def is_prime(x):
    if x < 2:
        return False
    elif x == 2 or x == 3: 
        return True
    else:
        # For numbers 2, 3, 4, 5, 6, 7, 8
        for n in range(2, x):
            # if 9 is divisible by any number above, return false (not prime) and end loop
            if x % n == 0:
                return False
                break
            else:
                return True

Now obviously, 9 is divisible by 3, so at that point the code should be returning 'False'. If anyone could explain why this is returning True when calling is_prime(9), I would be very grateful indeed!


#2

Hi! Mind posting a link to the lesson?


#3

Sorry, here you go:


#4

Your code looks fine. Only problem we have is that you're returning from inside a conditional. Here's my code:

def is_prime(x):
    Prime = False
    if (x < 2):
        Prime = False
    elif (x == 2):
        Prime = True
    else:
        for n in range(2,x):
            if ( x % n) == 0:
                Prime = False
                break
            else:
                Prime = True
    return Prime

See how I return Prime that I define earlier? Python has a weird thing with conditionals that breaks your code if you return from inside it. Try doing something like I did, and it should work.


#5

Well that fixed it!

I defined a 'prime' variable before the first if statement, and then changed all 'return' functions to set the 'prime' variable, exactly the same as you've shown with your code, and it's worked!

So is this a quirk of python then? I'll bear in mind in future that Python doesn't like returning from inside a conditional.

Thank you for your help!


#6

In many cases, yes. This is a quirk, so personally, as a general rule, I will include that variable just for the sake of debugging.


#7

Just add
def is_prime(x):
if x < 2:
return False
elif x == 2 or x == 3:
return True
else:
# For numbers 2, 3, 4, 5, 6, 7, 8
for n in range(2, x):
if x % n == 0:
return False
break
n +=1 #this made the difference!!! try it
else:
return True


#9

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