Is_prime


#1

I have define the is_prime function as followed:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range (2, x-1):
if x % i == 0:
return False
else:
return True
Of which I would get the error" Oops, try again. Your function fails on is_prime(3). It returns None when it should return True."

It turns out that if I remove the else: and the indentation highlighted in bold, as followed:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range (2, x-1):
if x % i == 0:
return False
return True
This would work.
Can someone please explained to me why my first code doesnt work and the second code works?

Thanks.


#2

why x-1 in range? Range doesn't include the stop value (in this case x)

Well, a number (for example 13) is only a prime number when its not divisible by any number between 2 and x (13 for example)

so, you want to return True after the loop. If a number is not a prime number, return False will end the function


#3

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