[PYTHON] EP 12 Avoid else Blocks After for and while Loops.

  • Python has special sytax that allows else blocks to immediately follow for and while loop iterator blocks

Effective Python

>>> for i in range(3):
...  print("Loop %d" % i)
... else:
...  print("Else block")
...
Loop 0
Loop 1
Loop 2
Else block

Fun behavior

>>> for i in []:
...  print("Nothing")
... else:
...  print("Elese block")
...
Elese block

>>> while False:
...  print("Nothing")
... else:
...  print("Else block")
...
Else block

The rationale for these behaviors is that else blocks after loops are useful when you're using loos to search for something.

>>> a = 4
>>> b = 9
>>> for i in range(2, min(a, b) + 1):
...  print("testing %d" % i)
...  if a % i == 0 and b % i == 0:
...   print("Not coprime")
...   break
... else:
...  print('Coprime')
...
testing 2
testing 3
testing 4
Coprime

But in real world, the helper function could be used.

def coprime(a, b):
    for i in range(2, min(a, b) + 1):
      if a % i == 0 and b % i == 0:
        return False
    return Tru

Recommended Posts

EP 12 Avoid else Blocks After for and while Loops.
Effective Python Note Item 12 Avoid using else blocks after for and while loops
Avoid nested loops in PHP and Python
while else