https://www.oreilly.co.jp/books/9784873117560/ P23~25
Usually, else blocks in programming languages are mainly used to mean "if the upper block is not implemented, do this". But not in python
for i in range(3):
print('Loop %d' % i)
else:
print('Else block')
>>>
Loop 0
Loop 1
Loop 2
Else block
In this way, the else block is executed after the for loop has completed execution. Also, a mysterious specification that the else block is not executed if break is executed immediately before.
for i in range(3):
print('Loop %d' % i)
if i == 1:
break
else:
print('Else block')
>>>
Loop 0
Loop 1
In addition, looping through an empty sequence will immediately execute the else block.
for i in []:
print('Never runs')
else:
print('Else block')
>>>
Else block
Furthermore, if it fails at the beginning of the while loop, it will be executed as it is.
while False:
print('Never runs')
else:
print('Else block')
>>>
Else block
It is useful when processing information after a loop. For example, when checking whether two numbers are relatively prime (the common divisor is not outside the first place), if the common divisor is found on the way to try every number, it can be judged that it is not prime, but it loops to the end. If it is not found, it can be judged to be disjoint. This specification is useful here.
a = 4
b = 9
for i in range(2, min(a, b) + 1):
print('Tasting', i)
if a % i == 0 and b % i ==0:
print('Not coprime')
break
else:
print('Coprime')
>>>
Tasting 2
Tasting 3
Tasting 4
Coprime
It seems that it is only useful if the previous block has a break check.
Then you should write a separate helper function to make it smarter.
** Conclusion If possible, avoid using else blocks in loops **
Recommended Posts