[PYTHON] EP 12 Eviter les autres blocs après les boucles pendant et while.

  • 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 Eviter les autres blocs après les boucles pendant et while.
Élément de note Python efficace 12 Évitez d'utiliser des blocs else après les boucles for et while
Évitez les boucles imbriquées en PHP et Python
tandis que d'autre