Loop Else in python
-
The
elseblock can be used with bothforandwhileloops. -
The
elseblock executes when the loop finishes normally. -
If the loop is terminated using
break, theelseblock does not execute.
Example 1: for Loop with else
for num in range(1, 4):
print(num)
else:
print("Loop completed successfully")
Output
1
2
3
Loop completed successfully
Example 2: while Loop with else
count = 1
while count <= 3:
print(count)
count += 1
else:
print("Loop ended normally")
Output
1
2
3
Loop ended normally