简体   繁体   中英

Python: for loop between if-else, how/why does this work?

I'm currently going through the Lynda Python tutorial and in the section on generators I see the following code:

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

I didn't catch it at first, but as I was going through the code I noticed that the else keyword had an entire for-loop between it and an if at the same indentation level. To my surprise, the code not only runs, it actually produces the correct behavior.

If I were to replace the for-loop with a simple print("Hello, World") statement, only then do I get an expected interpreter error.

What was the reasoning behind this syntax, and why does it work with loop statements but not others like print() ?

For reference, I would have expected the code to be written like the following:

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

An else: block after a for: block only runs if the loop completed normally. If you break out of the loop, it won't run. In this case, this makes no difference because you never break out of the loop; you return before it ends or you let it complete normally.

The reason for this behavior is that in python for loop actually can be followed by else statement. Else branch is executed in case of usual loop finish and is skipped after breaking .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM