For Else in python

10 Mar 2021

This was new to me! While putting together a Python course on make things I ended up with a piece of code that didn’t behave as expected. It turned out I’d incorrectly indented an else inside a for loop accidentially creating a for-else loop:

for number in range(22,25):
  if number % 7 == 0:
    print(f"found a multiple of 7: {number}")
    break
else:
  print("didn't find a multiple of 7")

You need the break statement, otherwise the else clause is executed after the for loop finishes.