2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Edu Rod
  • 31
  • 3
  • Have you read [the documentation for the `for` statement](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement)? What does it tell you? – Some programmer dude Nov 04 '20 at 02:00
  • It's not about indentation. Your code now does not have an `if-else`. What you have is `for-else`, which is a valid Python construct. See [Why does python use 'else' after for and while loops?](https://stackoverflow.com/q/9979970/2745495). – Gino Mempin Nov 04 '20 at 02:01
  • Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Gino Mempin Nov 04 '20 at 02:02
  • By the way, "***I*** made this... but I don't understand... " That implicates you don't know what you're doing, that you're just guessing and hoping for the best. Not a good way to learn programming. – Some programmer dude Nov 04 '20 at 03:31
  • 1
    Don't listen to all this criticism, it's easy to be confused by the for-else. It's an unusual construct not present in many other languages, and it's rarely used in python. It may also be present on a while loop. – President James K. Polk Nov 04 '20 at 13:44

2 Answers2

3

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.

nullUser
  • 1,601
  • 1
  • 12
  • 29
2

From the documentation: "The break statement, like in C, breaks out of the innermost enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."

https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops