I am a Python beginner. I find that the else in for–else and while–else is completely unnecessary. Because for and while will finally run to else, and we can use the usual lines instead.
For example:
for i in range(1, 5):
print i
else:
print 'over'
and
for i in range(1, 5):
print i
print 'over'
are the same.
So why does Python have else in for–else and while–else?
You are wrong about the semantics of for/else. The else clause runs only if the loop completed, for example, if a break statement wasn’t encountered.
The typical for/else loop looks like this:
Think of the “else” as pairing with all of the “if’s” in the loop body. Your samples are the same, but with “break” statements in the mix, they are not.
A longer description of the same idea: http://nedbatchelder.com/blog/201110/forelse.html