Python “for else” Statement

Python provides the for loop in order to iterate over multiple items easily. The for else statement is not a well-known statement which can be usefull rarely. We can use both for and else statements together to iterate over a list and if the for iteration is not end with the break statement the else statement is executed.

Use “for else” Statement

We generally use the for else statement in order to iterate over a list and check some item’s existence or case. If we found it we use the break statement in order to exit from the for loop. If the “for loop” is not broken we may want to take some action by using the else statement which is executed if the “for loop” break statement is not executed.

numbers = [3,5,1,5,6,2]

for number in numbers:
   if a== number:
      print(a," found")
   print(a," not found")

Leave a Comment