[PYTHON] EP 12 Vermeiden Sie sonst Blockierungen nach for- und while-Schleifen.

  • 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 Vermeiden Sie sonst Blockierungen nach for- und while-Schleifen.
Effektiver Python-Hinweis Punkt 12 Vermeiden Sie die Verwendung von else-Blöcken nach for- und while-Schleifen
Vermeiden Sie verschachtelte Schleifen in PHP und Python
während sonst