In Python, we can have the else statement associated with a loop statement. If the else statement is used with a for loop, the else statement is executed when the loop has completed iterating. But when used with the while loop, the else statement is executed when the condition becomes False.
Example 1:
a="welcome" for i in a: print(i,end=" ") else: print("\nCompleted")
Output:
w e l c o m e
Completed
Example 2:
i=1 while(i<0): print("Python") i=i-1 else: print(i,"is not negative so the loop dis not execute")
Output:
1 is not negative so the loop dis not execute
Leave a comment