python-3.xfor-else

For loop with an else and one iteration


I have a for loop that loops through a dynamic list of contact objects, and checks if the contact email meets a specified condition. I used an else statement with the for loop to return a "Sorry condition not met", when the list is exhausted. This approach works fine except when the list has only one contact, which satisfies the condition. In this scenario, both the body of the for loop and the else portions are executed.

Kindly advise on how to let the interpreter ignore the else part for one iteration that meets the set condition.

def searchContact(self, search_name):
    print("Your search matched the following:")
    for contact in self.contacts:
        if search_name in contact.name:
            print(contact)
    else:
        print("Sorry that contact does not exist!!")

Solution

  • As user2357112 mentions, and as stated in the Python docs here

    a loop’s else clause runs when no break occurs

    You could try something along the lines of:

    def searchContact(self, search_name):
        contact_found = False
    
        print("Your search matched the following:")
        for contact in self.contacts:
            if search_name in contact.name:
                contact_found = True
                print(contact)
    
        if not contact_found:
            print("Sorry that contact does not exist!!")