So this is more of a question as to why my code works correctly. I had been messing with this code for sometime and after changing the indent on 'return True' it came out as correct. Before, I had it directly under the 'if' statement within my 'for' loop.

My question is:

Why doesn't x = 2 return as False when I have my 'return True' statement outside of this loop?

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


Remember, 2 is Prime. It's the only even number that is (by its very nature it is a factor of all even numbers) so it can be allowed to walk around the loop.

if x > 2:
    # loop over divisibles
        return False

return True


Right. I know 2 is prime, but when i used the 'for n in range (2, x)' statement its my understanding that 'x' is not inclusive, but since my range begins at 2 wouldn't that make the range from 2 to 2? or would my range now be 2 to 1 which bumps it out of my loop?


and why can't my 'return True' statement be under my last 'if' statement?


effectively bypassing the loop. The return value should be True. The if statement (mine from above) isn't even needed.


Because that would put it inside the loop. We want only False outcomes to be returned within the loop confines. Anything else will fall through.


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