python

Use of else condition with for loop in Python

Else conditional statement can be used with python for loop if the break statement does not execute inside for loop.

#Using else with for loop
for i in range(4):
    print(i)
else:  # Will execute after loop completed if no break statement
    print("I am in else")

#else will not be executed if 'break' executed used inside loop
for item in ['one', 'two', 'three']:
    if item == 'two':
        break
    print(item)
else:
    print("This will not be executed")
Output
0
1
2
3
I am in else

one

Unlike other programming languages, you can use else conditional statement with for loop in python.

In the first code snippet, we are printing the message 'I am in else' when the for loop is completed. If you are using the 'break' keyword inside for loop and it executes inside the for loop then the else conditional statement will not be executed.

Was this helpful?