Why does this Else statement need to be outside the For statement?


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

So this is my code and it works, but I don't understand why the else statement needs to be outside the If statement? Shouldn't it go If (statement) and if that isn't true it should go do the else statement to return True. But if I indent the Else statement at the end of the code the error comes up with "IS_Prime(2) comes back as null, not True". Can someone please explain to me why the indentation works that way, it just makes no sense to me


#2

Because we need the loop to fully complete. If it does, then that means the number is prime. If it does not, then the number is not prime. Were the else to be part of the if statement, it would return false positives.


#3

Your code is equivalent to this:

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

(remove the else)

If you want something to be different from that then you'll have to consider why that would be better and what it's supposed to accomplish.

Your else does not interact with your if at all, what you have is a for-else, but the else isn't really doing anything, which is why it can simply be removed.


#4

... in this instance. There is a reason for else in a for statement that has to do with whether or not the loop was terminated with break. That's for further reading though. Belay this post.


#5

Right, it's not that for-else is a completely useless language construct, it's that it isn't being used here as intended. The use here is similar to doing:

if True:
     print('hello')

where the if is totally unecessary