In Python programming, we can use `else` with the for loop. This might seem a bit counterintuitive at first, as we usually associate else with conditions that are not satisfied, but in the case of loops, it has a different role.
Basic syntax:
for counter in sequence:
# Statements inside the for loop block
else:
# Statements inside the else block
PythonThe else block in a for loop is executed when the loop has iterated over the entire sequence without any break statement. It is not executed if any break statement is used in the loop. Let’s see an example:
for x in range(5):
print(f"Iteration no {x+1} in the for loop")
else:
print("Else block in the loop")
print("Out of the loop")
PythonThe Output Of This Code Will Be:
Iteration no 1 in the for loop
Iteration no 2 in the for loop
Iteration no 3 in the for loop
Iteration no 4 in the for loop
Iteration no 5 in the for loop
Else block in the loop
Out of the loop
PythonIn this example, the else block is executed after the for loop completes all its iterations. If there were any `break` statements inside the for loop the else block never executes. Let’s see the example:
for x in range(5):
print(f"Iteration no {x+1} in the for loop")
if x == 3:
break
else:
print("Else block in the loop")
print("Out of the loop")
PythonThe Output Of This Code Will Be:
Iteration no 1 in the for loop
Iteration no 2 in the for loop
Iteration no 3 in the for loop
Iteration no 4 in the for loop
Out of the loop
PythonThe else clause in a loop can be useful when you want to perform some actions after the successful completion of the loop, such as finalizing or cleaning up operations.
If you don’t know the “Dictionary& Its Methods In Python.” just click on Read More.
I hope you understand “For Loop With Else In Python” Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀