# Is_prime issues with the number 2 - getting 'None'

#1

Hi! I am very new to python but getting the hang of it thanks to CA. I have 2 questions:

1 - why is 2 evaluating as None?

def is_prime(x):
if x < 2:
print 'hi-a'
return False
else:
print 'hi-b'
for n in range(2, x-1):
if x % n == 0:
print 'hi-ci'
return False
else:
print 'hi-cii'
return True

print is_prime(2)

This gives me ‘None’ instead of ‘False’. Any reason why this could be?

2 - Why is the range supposed to be:

range(2, x-1)

I think it should be:

range(2, x)

as this gives a list of, with x = 5, of 2, 3, 4 which is what we need. But the x-1 gives a list of 2, 3.

Really confused and any help would be really appreciated.

#2

the loop never runs, you should see that with the print statements. 2 < 2 is false, so the loop never runs.

well, you shouldn’t include x in your loop, which is why the instructions state x-1, but range() doesn’t include stop value, so x is good for stop value of range.

#3

I understand that 2 < 2 is False, but shouldnt it then evaluate the first ‘else’ and do 2 % 2?

Also, follow up to the second, I understand that you want the range to be less than x, but if the model answer is x-1, wouldnt that in fact be x-2 as range(,x) already implicitly does x-1?

#4

no, given the else is nested inside the loop, and the loop won’t run, so it never reaches the else clause

no, x-1 is only a notation to indicate that we don’t want to have the value of x. But range already does this, so we can just do range(2, x)

#5

Consider in your loop if x is factorable, (divisible) then return False, else do nothing, so no else clause. Have your program return True after the loop.

#6

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