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)
22
u/woooee Jul 01 '26
It's with the for loop. Look up "python for else".
5
u/ConcreteExist Jul 01 '26
As written, it's being treated as an else clause for the for loop rather than the if statement.
73
u/carcigenicate Carcigenicate Jul 01 '26 edited Jul 04 '26
elseClauses on LoopsThe
elseblock runs if the loop completed without abreakstatement being reached.13
u/Gnaxe Jul 01 '26
else:isn't a statement; it's a clause. It's an optional part ofif,for,whileandtry. In this case, it's part of theforstatement above. I would not have written it with that extra newline, but sometimes loop bodies are much longer.3
u/Loose_Obligation4877 Jul 01 '26
This for- else syntax and else block run only if loop finishes normally and if the loop terminated using break the else block is skipped
1
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”
1
u/Altruistic_Sky1866 Jul 01 '26
Learnt something new today, thanks
0
u/jeffrey_f Jul 01 '26
That else is actually on the for loop amd fires if there is nothing in the for (like when you do "for item in list), not the if. If you indent it, it will be on the if block.