# Is_prime

#1

This code is right.

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

However, below is wrong. But I don't understand why.

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

Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.

#2

on second else is indented too much

#3

I know it, but I think the "else" shoud follow "if" rather than "for". However, it is wrong.

#4

if can work on its own, for can use else too, you need to understand logic

#5

If so, elif is unnecessary. But I still don't understant why is_prime(9) turned out wrong in the second code.

#6

if x is smaller than 2 return false, else is some range, if condition is met return false, if not in that range return true

if you put else inside for your if and else will return false or true while in some range

#7

I can understant what you said, so I deleted the elif and the code is still right. But I think "9" is in that range, and 9 %3 == 0 is true, so it should return False rather True. But the "Oops,..."

#8

``````     if x %n == 0:
return False
else:
return True``````

this means you leave the function in this step no matter what so if 9%2 fails you pick the other case which is to return True.

#9

yeah, but range is (2, x-1)

#10

You're right, I get it. Thanks.

#11