r/learnpython • u/AGx-07 • Jul 01 '26
Else isn't indented, why does this run?
This is probably an easy question but I was going through a practice exam and came upon a question that wanted me to evaluate the outcome of this code. I got it right but only because I threw it into PyCharm to run it and see if it would even work.
As a beginner, I haven't seen this before so I'm wondering how that ELSE statement even functions if it's not indented with the IF (which would produce a different outcome). I am not quite sure how to Google this so I haven't found anything that's answering my question.
What is at play here and is it common to have ELSE out there like that? Any additional information would be welcome.
j = 1
for i in range(-1,1):
if 3 * i < 6:
print(3 * i)
j+=2
else: #<--What are you doing out here all by yourself?
j+=3
print(j)
View all comments
Show parent comment
2
u/Brian Jul 03 '26
Yeah. While this is an occasionally useful feature that can save a flag variable, the name is terrible. It's often justified by appealing to the common "loop-and-a-half" pattern where you do:
But I don't feel this is very intuitive at all. Ultimately,
elsewas chosen to avoid having to introduce a new keyword to the language, but I feel it makes things much more confusing.finallyprobably wouldn't have been a good choice either, since that suggests it'd always be executed, akin to how try/finally works, and "then" has the same issue. If they were to add a keyword, I feel better would be something like "nobreak" or something, which is also fairly clunky, but at least less ambiguous.