Python allows the else keyword to be used with the for and while loops too. The else block appears after the body of the loop.
The program exits the loop only after the else block is executed.
The statements in the else block will be executedafterall iterations are completed.
Syntax
for counter in sequence:#Statements inside for loop blockelse:#Statements inside else block
Example:
for x inrange(5):print(f"iteration for {x+1} in for loop")else:print("else block in loop")print("Out of loop")
Output:
iteration no 1infor loop
iteration no 2infor loop
iteration no 3infor loop
iteration no 4infor loop
iteration no 5infor loop
else block in loop
Out of loop
Notes:-
After Breaking loop, the else will not be printed.
Example:-
for i in[]:# creating empty listprint('nope')breakelse:print('this will not be printed as loop is broken')
Output:
# as loop is broken
Else will be printed only if loop's condition is not met, like in the end of the loop when conditions are met and loop is finished.....