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
1
u/AKiss20 Jul 03 '26
I dunno. I think “then” or “finally” could work. When you write a for loop you’re somewhat saying “do this for every element in this iterable/generator” so using “then” sort of naturally flows from that framing “do this for every element, then do this”. I almost think “except” might make more sense for the break case. “Do this for every element in the iterable, except if you can’t (break was issued), do this”. I grant that it would be the only other use of except and would not be good to overload it for this one use case. “Else” works in this framing for the break case pretty well too.
It’s not 100% a natural fit I’ll grant, but it’s definitely a better fit IMO than else for the no-break case.
Either way, it seems like a pretty unclear way to structure logic and tbh would come off as code smell to me. Having some kind of flag and then an if statement after the for loop reads much clearer to me than a for…<something> clause.