MWZ

MINDWAREZONE

Loop Else in python

  • The else block can be used with both for and while loops.
  • The else block executes when the loop finishes normally.
  • If the loop is terminated using break, the else block 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