I feel my question has been asked, but I haven't gotten an answer out of previous posts in the forums. So here's my code:
def is_prime(x): if x == 2: return True elif x > 1: for n in range(2, x-1): if x % n == 0: return False else: return True else: return False
After testing some numbers, and printing the results, I've found this code works perfect for any numbers not 3 or 9. I'm not sure why this isn't working for me, as when I run the number through the code in my head it should work. Here's my process of thought.
1) The code checks if x == 2, if it does then returns True.
2) If x != 2, then it runs through my loop. The loop checks if x is divisible by any number "n" between 2, and x-1. Meaning if this was the number 3, it would go through the range 2, 2. Or if x = 9, then it would run through the range 2, 8.
3) If x % n == 0 it is not a prime number because there is no remainder. On the other side of things, if x % n does have a remainder for n in range(2, x-1), then it is prime.
4) Else, the number is 1 or 0, which is not a prime, so it would return False.
So why then does 3 and 9 not work in this loop? The "n" range for 3 would be 2,2. 3/2 leaves a remainder, yet returns "none". 9 would have a range (2, 8) where 3 is in that range. 9/3 would leave no remainder, yet it still returns True. It has nothing to do with multiples of 3 in total as 12 returns False. Please help!