# IS prime indentation question

#1

Spent a long time on the is_prime exercise. I previously had:

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

this failed when it tried to pass is_prime(9), saying that it said True when it should of said False. I changed up the indentation at "else" at the "elif x>= 3". Shown below:

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

so basically it wanted the "else: return True" under the elif to be aligned with the "for n in ...". why did it want that? wouldn't that "else" be aligned with the "if"? the "if" says if its divisible evenly, then False, and my else would say return True, which is based on the results of that "if". What do you ya'll think? or did I confuse you? cause I think I just confused myself

#2

run this code:

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

now in the first iteration of the loop, a return keyword is reached so either if is true and False is returned or else will return True.

a function ends the moment a return keyword is reached. So if you have `if/else` the first value of the loop will determine if the number is a prime

but you only want to return true if x is not divisible by values between 2 (included) and x (excluded), that is why you place return True outside the for loop

#3

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