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

PythonServer Side ProgrammingProgramming

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
raja
Published on 17-Feb-2018 12:54:08
Advertisements