is_prime


#1

def is_prime(x):
tab if x == 2 or x == 3:
tab tab return True
tab elif x < 2:
tab tab return False
tab for n in range(2, x - 1):
tab tab if x % n == 0:
tab tab tab return False
tab tab else:
tab tab tab return True

My function fails on is_prime(9). It runs true instead of false. Why?


#2

Nevermind, I just found the same question in another thread.


#4

For anyone curious, when a function returns a value the function stops running. I didn't remember seeing this in previous lessons, but it appears very useful to know.

In this case, the first value in range(2,x-1) for x=9 is 2, so it checks if 9 % 2 == 0, which it does not since the remainder is 1 from the modulus operator, then runs the else condition to return True and breaks.

While it works to return a value of False when the function finds a factor and determines it cannot be prime ever past that point, when it tests each non-factor in the range it should not return True because then it will break on the first non-factor (in this case 2 for any odd number, which all prime numbers above 2 are) and give an incorrect result.