for ... else ...
For loops also have anelse
clause which most of us are unfamiliar with. Theelse
clause executes when the loop completes normally. This means that the loop did not encounter anybreak
.
The common construct is to run a loop and search for an item. If the item is found, we break the loop usingbreak
. There are two scenarios in which the loop may end. The first one is when the item is found andbreak
is encountered. 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 theelse
clause.
This is the basic structure of afor/else
loop:
Consider this simple example which I took from the official documentation:
It finds factors for numbers between 2 to 10. Now for the fun part. We can add an additional else
block which catches the numbers which are prime and tells us so:
Reference: http://book.pythontips.com/en/latest/for_-_else.html
Last updated