Python For Else
Python tip:
You can use
else
withfor
loops when searching for something. Code inside theelse
will be executed if the break statement isn't hit.items = ["right_one", "my_item", " another_item"] def right_one(item_to_check): if item_to_check == "right_one": return True else: return False for item in items: if right_one(item): print("Do something with the item") break else: print("I will do something else, no item to process") """ Do something with the item """ items = ["different_item", "my_item", "another_item"] for item in items: if right_one(item): print("Do something with the item") break else: print("I will do something else, no item to process") """ I will do something else, no item to process I will do something else, no item to process I will do something else, no item to process """