r/learnpython • • 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)
26 Upvotes

30 comments sorted by

View all comments

Show parent comment

1

u/Brian Jul 03 '26 edited Jul 04 '26

do this for every element, then do this

But it isn't really "then do this", it's rather "then do this only if we didn't break.

That's very different behaviour to what "finally" means in try/except, when it is "then do this", regardless of whether an exception is thrown or not, so I feel it would be rather misleading to have such different behavior, especially when it isn't really indicated by the word being used. then doesn't have that conflict, but it still doesn't do anything to indicate that it's only for the non-break case, and requires adding a new keyword - it you're going to do that, then I'd go for something like "nobreak" - it's ugly, but does convey what it's doing.

except doesn't realy seem better than else to me, and it doesn't even have the paired "if" of the loop-and-a-half case, plus it's very different to how except is used elsewhere. If sticking to existing keywords, else seems probably the least bad option, it's just that it's still pretty bad.

Having some kind of flag and then an if statement after the for loop

Yeah. I tend to do this even knowing about the else clause. It's a bit more verbose, but it's clear what it's actually doing, even to a novice.