I was going through this. Coming from C environment, it hit me right in the face with utter surprise and disbelief. And, then I tried it for myself::
bCondition = True
while bCondition:
print("Inside while\n")
bCondition = False
else:
print("Inside else\n")
print("done\n")
This code renders the below output,
#Output
Inside while
Inside else
done
Now, my question is, Why? why do we need this? Why both the blocks are executed? Isn't if
and else
were made for each other, then what use case will make this design a useful design to implement?
Again if we just change the code to incorporate a break
, the behavior is more mysterious. Ideone Link.
bCondition = True
while bCondition:
break
else:
print("Inside else\n")
print("done\n")
This code renders the below output,
#Output
done
Why both of the blocks are skipped? Isn't break
made to break out of the loop only, then why is it breaking out of the else
block?
I went through the documentation too, couldn't clear my doubts though.