0

I noticed what I thought of as strange behavior in python (tested in versions 3.6.9 and 2.7.17) code I was developing and distilled it into the below where an else statement that I had misplaced at a level of indentation to be within the previous elif gets executed every time. I think that instead it should be caught as an error (I had meant to put it at the same indentation (no indentation) as the previous if and elif. I think that the else doesn't have an if that it belongs to. Thanks in advance for any insight or comments. Demonstration program:

if 0:
    print(0)
elif 1:
    for i in range(3):
        print(i)
    else:
        print('how is this possible')

Program output:

$ python -i tmp.py
0
1
2

how is this possible?

PS: my code works as expected when the else has no indentation so I don't have a need to fix anything except my understanding (no rush).

Patrick
  • 1,189
  • 5
  • 11
  • 19
Tom
  • 1
  • 2
    The `else` belongs to the `for`, not the `if`. See this for example https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops – Matt Hall Oct 12 '22 at 15:42

0 Answers0