Flavors of `else` in Python
Python’s loop statements have a feature which most of us are unfamiliar with, an
For loops also have an else clause The else clause executes when the loop completes normally(without encountering any break statements). The basic structure of a for/else loop:
Possible use cases:
- Searching an item in a list/iterable: This can be achieved by running a loop and comparing each item. There are two scenarios in which the loop may end. The first one is when the item is found and we break the loop using the
breakstatement. The second scenario is that the loop ends. Now we may want to know which one of these is the reason for a loops completion. One method is to set a flag and then check it once the loop ends. Another is to use the else clause.
- Try/Else completion clause:
Elseclause can be used with
Elseclause in a try statement means that the try block completed successfully i.e didn’t throw any exception.