#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")
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.
0 Comments