2

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 ?

Srini
  • 23
  • 2
  • Related post: http://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops – gr3co Aug 08 '13 at 02:25
  • 1
    Paraphrasing Raymond Hettinger, "if we had just called it `nobreak`, nobody would ever be surprised by it." – roippi Aug 08 '13 at 02:27

2 Answers2

7

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'
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
3

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.

jh314
  • 25,902
  • 15
  • 60
  • 80