Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for-else relationship [duplicate]

Tags:

python

syntax

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 ?

like image 881
Srini Avatar asked Dec 04 '25 03:12

Srini


1 Answers

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'
like image 71
Ignacio Vazquez-Abrams Avatar answered Dec 06 '25 16:12

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!