Python for loop with else

As we know, In most of the programming language the use of else statement has been restricted with the if conditional statements. But in python we can implement else condition with for loop also. 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.

Else block is executed in below program:

for i in range(5):
    print(i)
else:
    print("for loop is executed!!!")

Output:

0
1
2
3
4
for loop is executed!!!

Else block is NOT executed in below program:

for i in range(5):
    print(i)
    break;
else:
    print("for loop is executed!!!")

Output:

0

Note: Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.

def odd_even(l):
    for i in l:
        if i%2==0:
            print ("Even Number-",i)
        else:
            print ("Odd Number-",i)
    else:
        print("Else loop is executed successfully")

odd_even([1,2,3,4,5]) 

Output:

Odd Number- 1
Even Number- 2
Odd Number- 3
Even Number- 4
Odd Number- 5
Else loop is executed successfully
Tags