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 afor:block only runs if the loop completed normally. If youbreakout of the loop, it won’t run. In this case, this makes no difference because you never break out of the loop; youreturnbefore it ends or you let it complete normally.