I can run the below python script without errors.
for n in range(3):
print n
else:
print "done"
But I am puzzled about the else without a matching if.
It does not make sense.
Can some one explain why this works ?
I can run the below python script without errors.
for n in range(3):
print n
else:
print "done"
But I am puzzled about the else without a matching if.
It does not make sense.
Can some one explain why this works ?
The else
clause of for
and while
only executes if the loop exits normally, i.e. break
is never run.
for i in range(20):
print i
if i == 3:
break
else:
print 'HAHA!'
And the else
clause of try
only executes if no exception happened.
try:
a = 1 / 2
except ZeroDivisionError:
do_something()
else:
print '/golfclap'
The body of the else
is executed after the for
loop is done, but only if the for
loop didn't terminate early by break
statements.