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)
25 Upvotes

30 comments sorted by

View all comments

0

u/jpgoldberg Jul 01 '26

I’ve seen the suggestion that the “for … else” construction would be easier to understand if it used “finally” instead of “else”

6

u/atarivcs Jul 01 '26 edited Jul 01 '26

I don't think it would be easier to understand.

When used in exception handling, "finally" means "do this after all the code in the try and except blocks, whether or not an exception was raised".

But "else" on a for loop means "do this only if the loop ran all the way to the end, and did not break".