while else in python



"else" block will be executed after the termination of the while loop. If the while loop gets break else block will not be executed.



Syntax:



while(condition):

       #looping

else:







Example-1
i = 0;

while(i<5):
    
    print(i)

    i += 1

else:
    
    print("Loop completed") 


Output



0
1
2
3
4
Loop completed







Example-2
i = 0;

while(i<5):
    
    if(i == 3):
        break
    
    print(i)

    i += 1;

else:
    
    print("Loop completed")


Output



0
1
2