6/15 - is_prime


#1

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

Why this code doesn't work and the next one does?

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

Why the return True in the second one have to be outside the for loop? Shouldn't it be inside?


#2

Just because a number is not divisible by one number doesn't mean it won't be divisible by the next one in the loop, meaning there is still a possibility of not being a Prime. We mush complete the entire iteration process before we can conclude primeness. That is why return True is outside of the loop, in function block scope.


#3

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