mardi 3 novembre 2020

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

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.

Aucun commentaire:

Enregistrer un commentaire