In this article, we will be learning about loop-else statements in Python 3.x. Or earlier. In this tutorial, we will focus on for loop & else statement way of execution.
In other languages, the else functionality is only provided in if-else pairs. But Python allows us to implement the else functionality with for loops as well .
The else functionality is available for use only when the loop terminates normally. In case of forceful termination of loop else statement is overlooked by the interpreter and hence its execution is skipped.
Now let’s take a quick glance over some illustrations to understand the loop else statement in a better manner.
for i in ['T','P']: print(i) else: # Loop else statement print("Loop-else statement successfully executed")
T P Loop-else statement successfully executed
for i in ['T','P']: print(i) break else: # Loop else statement print("Loop-else statement successfully executed")
Explanation − The loop else statement is executed in ILLUSTRATION 1 as the for loop terminates normally after completing its iteration over the list[‘T’,’P’].But in ILLUSTRATION 2 ,the loop-else statement is not executed as the loop is forcefully terminated by using jump statements like break .
These ILLUSTRATIONS clearly indicates the loop-else statement is not executed when loop is terminated forcefully.
Now Let’s look at an illustration wherein some condition the loop-else statement is executed and in some, it’s not.
def pos_nev_test(): for i in [5,6,7]: if i>=0: print ("Positive number") else: print ("Negative number") break else: print ("Loop-else Executed") # main function pos_nev_test()
Positive number Positive number Positive number Loop-else Executed
Explanation − Here as the else block in the if-else construct is not executed as if the condition evaluates to be true, the Loop-Else statement is executed.
If we replace the list in for loop [5, 6, 7 ] by [7, -1, 3 ] then the output changes to
Positive number Negative number
In this article, we learnt the implementation of loop-else statement and a variety of ways in which it can be implemented.