for .. else confusion
You seem to be confused by else
which is part of the for
loop.
You are not the only one.
In Python, for
loop might have at the end else
section, which is executed after all the loops are finished, unless there was break
statement. Yes, it is not very intuitive.
So you shall read the else
section as last part of the for
loop.
def looptest(loops=5):
for i in range(loops):
print "i", i
if i == 3:
print "in if"
return
else:
print "in else of the loop"
and try it for loops == 5:
>>> looptest(5)
i 0
i 1
i 2
i 3
in if
For number of loops 2 we do not expect return, we shall run through else
of the loop:
>>> looptest(2)
i 0
i 1
in else of the loop
Note, that return
must be within function, trying return on console would result in error.
range(2, 2) == []
Trying on Python console:
>>> range(2, 2)
[]
return
return ends up current function or run in the whole module. So after return
, no further code in the same part of your code is executed (with exceptions like try
, finally
, context managers etc, but this is not relevant to your code).