Is_prime


#1

i am having trouble understanding this code:

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


i don't understand why this doesn't work but if i place the last else statement with the for loop it works.
why does the else statement go with the for ..the if and else should be the part of for loop acc to me.
please help


#2

You will want to complete the loop before returning True. It does not need an else.


#3

Does that mean i never need an else dialog just to print the return False statement?
i can just get out of the inner loop and write return False?
for eg.
if x>10:
.......return True
return False
??
will this be valid?


#4

If x is divisible by n, then return False, otherwise do nothing. Let the loop play out and if there are no returns in the loop, the fall through will return True.


#6

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