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
Inside a for loop, you can use if statements as well.
If Statements test a condition and then do something if the test is True. For Loops do something for a defined number of elements.
If you want to combine for loop with if-else statements, then you have to specify if-else in front of for loop. If the condition satisfies, then the if block will be executed, otherwise the else block will be executed. A for-loop takes a list or sequence of elements.
No. The condition is evaluated ONCE when the code reaches the IF statement, and then the whole for loop would be executed without ever checking the condition again.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With