Skip to main content
  1. Posts/

The else Clause on Loops

··132 words·1 min·

Did you know for and while loops in Python can have an else clause?
#

It only runs if the loop completes without encountering a break — perfect for searching a collection when you want to run logic only if an item was never found, without extra flags.

Quick example:

for row in dataset:
    if row['target'] == 'desired_value':
        print("Found")
        break
else:
    print("Not found")

In this snippet, the else block executes only when the loop finishes without encountering a break. This lets you avoid creating extra flags or conditions outside the loop.

More information at the link 👇

Also published on LinkedIn.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano