Why does this Return False When x = 9?


#1

Would someone kindly explain to me why the following returns False when x = 9? Thanks :slight_smile:

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

FAQ: Learn Python - Practice Makes Perfect - factorial FAQ: Learn Python - Practice Makes Perfect - is_prime
#2

Hi @ethancohen7,

9 isn’t a prime number. When divided by 3, the remainder is 0, so you should get False returned on line 9.


#3

i am confused by the question, if we use x=9:

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

print is_prime(9)

we can see the function returns True. So your function says 9 is a prime number, but lik zystvan says, 9 is not a prime number, your function should return False


#4

What is happening is that when the line below runs:

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

The program will only ever check if x % 2 is true when n = 2. Therefore, all composite numbers that do NOT have the number 2 as a factor will return True. This is because this for statement will only ever run one time-- it will return False if it’s divisible by 2 and return True if this is not the case. I understand why this is happening, but I can’t quite articulate it, so here’s the code with changes made by me:

def is_prime(x):
	if x < 2:
		return False
	elif x == 2:
		return True
	else:
		for n in range(2,x):
			if (x % n) == 0: # checks if x is divisible by n
				return False
			elif n == x - 1: # checks if x is divisible by x-1 (the highest value n can ever take on)
				return True
			else: # if x is not divisible by n and the value of n has not yet reached x - 1,
				continue

IF: checks if x is divisible by n
ELSE IF: checks if x is divisible by x-1 (the highest value that n can ever take on)
ELSE: if x is not divisible by n and the value of n has not yet reached x - 1, continue the loop (This isn’t necessary)