I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
Many beginners accidentally stumble on this syntax when they try to put an if
/else
block inside of a while
or for
loop, and don't indent the else
properly. The solution is to make sure the else
block lines up with the if
, assuming that it was your intent to pair them. This question explains why it didn't cause a syntax error, and what the resulting code means. See also I'm getting an IndentationError. How do I fix it?, for the cases where there is a syntax error reported.
See also Why does python use 'else' after for and while loops? for questions about how to make good use of the feature.