LoginSignup
1
1

More than 5 years have passed since last update.

EP 12 Avoid else Blocks After for and while Loops.

Posted at
  • Python has special sytax that allows else blocks to immediately follow for and while loop iterator blocks
  • The else block after a loop only runs if the loop body did not encouner break
  • Avoid using else block after loops because their behavior isn't intuitive an be be confusing

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1