Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of "else" after "for" loop in Python? [duplicate]

Tags:

python

syntax

It seems both of the below codes are printing the same, then what is the need of "else" block after "for" loop in python.

Code 1:

for i in range(10):
    print i
else:
    print "after for loop"

Code 2:

for i in range(10):
    print i

print "after for loop"

Thanks in advance.

like image 920
Rajesh Kumar Avatar asked Dec 26 '22 09:12

Rajesh Kumar


2 Answers

From the documentation:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Follow the link for an example how this can be used.

like image 122
Aaron Digulla Avatar answered Jan 17 '23 17:01

Aaron Digulla


else executes after for providing for wasn't terminated with break:

for i in range(10):
    print i
    if i == 8:
        break # termination, no else    
else:
    print "after for loop"
like image 34
Dmitry Bychenko Avatar answered Jan 17 '23 18:01

Dmitry Bychenko