Understanding the Behavior of if, else in the For Statement

Asked 2 years ago, Updated 2 years ago, 19 views

This program determines the number of prime numbers up to 30

for i in range(2,30):
    for in range(2, i):
        if i%s == 0:
            break

    else:
        print(i)

I don't understand why if and else have different indents.
If else is indented the same as if, I understand that the result is wrong.

python

2022-09-30 19:34

1 Answers

The else corresponds to the else statement, but not to the for statement. The Python else statement (such as the else statement) can have a else clause until the end of the loop.

4.4.break and continue statements, and else Claims on Loops

From that perspective, if you double-check the behavior of the code you posted, you will be able to confirm that it is working as it should.

When I searched in English, I found a lot of arguments like "Why else", but it seems to end up as "it seems natural once you get used to it."


2022-09-30 19:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.