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 ?

2
  • Related post: stackoverflow.com/questions/9979970/… Commented Aug 8, 2013 at 2:25
  • 1
    Paraphrasing Raymond Hettinger, "if we had just called it nobreak, nobody would ever be surprised by it." Commented Aug 8, 2013 at 2:27

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for expanding on the original question by showing how it is used with try
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.