6 is_prime : Please Help


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

Why is this not working?


#3

The for loops will always execute.
It needs to be nested into an else after the ==2 or ==3 test


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

This worked. Thank you for your suggestions! Why does the last else need to be under the same indentation as for loop?


#5

Because it will only return true if the loop goes through but does not return false (doe not find a number that evenly divides the incoming value). It's part of the for ... else structure


#6

Thank you for your code!
Here is the shorter version of it.

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