How to use else conditional statement with for loop in python?


The else block in a loop (for as well as while) executes after all iterations of loop are completed and before the program flow exits the loop body. The syntax is as follows −

Syntax

while expr==True:
    #statements to be iterated while expr is true.
else:
   #this statement(s) will be executed afteriterations are over

#this will be executed after the program leaves loop body

example

for x in range(6):
print (x)
else:
print ("else block of loop")
print ("loop is over")

Output

The output is as shown below −

0
1
2
3
4
5
else block of loop
loop is over

Updated on: 27-Feb-2020

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements