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
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()
Example
Consider this example: It finds factors for numbers between 2 to 10.:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n/x)
break
We can add an additional else
block which catches the numbers which have no factors and are therefore prime numbers:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print( n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
Last updated