Else loop in Python

Else Loop : 

Other programming languages like c/c++/java , it has some restriction for using else conditional statement, i.e. we can not use else statement without if statement.But in python we can use else statement without leading if-statement. 

Python allows us to use else keyword with the for and while loops too. The else block appears after the body of the loop. The statements in the else block will be executed after all iterations are completed. 

use of else loop in python

Use : 

  • We can use else statement to check a loop has a break condition or not.
    • This type of condition is used when a loop has break statement and output depends on the fact that loop ends by itself or by using break statement

Code #1 :

#pyhton program 
#else statement 
 

b=10 
for i in range(5,11):
    if(i==b):
        break 
else:
    print(“loop ends after completing it’s iteration”)


Output:
#pyhton program 
#else statement 
 

b=10 
for i in range(5,11):
    if(i>b):
        break 
else:
    print(“loop ends after completing it’s iteration”)


Output:

loop ends after completing it's iteration

In the above program Else loop will be executed if and only if for loops terminates by completing it’s all iterations.

Code #2:

#pyhton program 
#else statement 
 
#to check does a word  contains ‘X’ in it
b=‘PrepInsta’             #here our word is PrepInsta
for i in range(len(b)):
    if(b[i]==‘X’):
        break 
else:
    print(“No prepInsta does not conatins X”)


Output :

No prepInsta does not conatins X

In the above program we can see that loop will terminates forcefully if an string contains character “X” in it. If Loop terminates due to if-statement inside the loop , the else statement outside the loop will not be excuted  and if loop terminates after completing all it’s iteration else statement will be executed.