6. is_prime


#1

I have no idea why this code isn't working. The code prints out the expected output above 2, however below 2 it doesn't work, and i don't know why! I tried to put in an elif statement to sought out the problem but it didn't work and i don't know why. Any idea where i am going wrong?

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


#2

How many iterations happen when x < 2?


#3

'''def is_prime(x):
for i in range(2,x):
print i
if x<2:
return False
break
elif x%i==0:
return False
break
else:
return True
''
ive changed the code to this now so it should get iterated the first every time, however when i input anything that its is below two, the loop doesnt break.'


#4

Fixed the problem, the constraint on the loop wouldn't work as when u entered <2 it would skip the For loop entirely as it wasn't within the specific range. To fix this i change the code to this : """
def is_prime(x):

if x>1:    
    for i in range(2,x):
        if x%i==0:
            return False
            break
    else:
        return True
else:
    return False

#5

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