For - else
else
Clause
else
ClauseExecutes after the loop completes normally. Ie., the loop did not encounter a break
statement.
Common use case
Run a loop to search for an item. If the item is found, we break out of the loop using the break
statement.
2 scenarios in which the loop may end:
when the item is found and
break
is encountered.The loop ends without encountering a
break
statement.
We may want to know which one of these is the reason for a loop’s completion. One method is to set a flag and then check it once the loop ends. Another is to use the else
clause.
Bluprint
Example
Consider this example: It finds factors for numbers between 2 to 10.:
We can add an additional else
block which catches the numbers which have no factors and are therefore prime numbers:
Last updated