I made this algorithm that tells you if a number is prime, but i don't understand why the 'if-else statement' on different indentation levels works

Viewed 59

This is the code:

def is_prime(p):
    for i in range(2, p):
        if p % i == 0:
            break
    else:
        print("Prime")


def main():
    p = int(input())
    is_prime(p)


main()

My question is, why the 'else statement' works if it's on another indentation level than the 'if'?, my guess is that because the 'for loop' is on the same indentation level that the 'else' is, the 'break statement' make the 'else' attached to the 'if', but i don't know.

2 Answers

The code is using a for-else clause, not an if-else clause!

for blah:
    do stuff
else:
    do more

The do more clause is executed if and only if you exit the for loop normally, i.e. without raising an error or using a break statement.

Related