# Problem with is_prime()

#1

For an unknown reason, my is_prime() function returns True if called with 9 when it shouldn't. 9 is divisible by 3 and I think that 3 is in the range for n, but the system doesn't seem to find this.

Here is my code:

``````def is_prime(x):
if x > 1:
if x == 2 or x == 3:
return True
#If x is evenly divisible by n, it is not prime.
#There may be a problem with iterating n.
else:
for n in range(2,x-1):
if x % n == 0:
return False
else:
return True
else:
return False``````

(I do think that my code is properly indented but this doesn't show up on my post.)

#2

We do not want to break the loop so remove the else and back the indentation on `return True` to line up with the `for`

``````def is_prime(x):
if x > 1:
if x == 2:                  # changed
return True
else:
for n in range(2,x-1):
if x % n == 0:
return False
return True             # changed
else:
return False``````

Not lesson tested but it does work in the console.

#3

Hello. I understand almost everything of your refined code but I am not sure the meaning of Line 9.

Why do we put "return True" here? Is it a short way saying "if x % n == 0, return False, otherwise (else), return True"? If so, can "else" simply be neglected here?

#4

We have progressed through the complete loop and are still here, meaning the number must be prime.

#5

I think I kinda get it. To help me better understand this, may I consider the "return True" is corresponding Line 2 "if x>1:" ?

#6

No connection. One is based upon state, the other upon outcome. They may look the same, but they are far removed.