带有 else 和一次迭代的 For 循环

For loop with an else and one iteration

我有一个 for loop 循环遍历联系人对象的动态列表,并检查联系人电子邮件是否满足指定条件。当列表用完时,我使用了 else 语句和 for loop 到 return 和 "Sorry condition not met"。这种方法工作正常,除非列表只有 one 联系人,满足条件。在这种情况下,for loopelse 部分的主体都被执行。

请指教如何让解释器在满足设定条件的一次迭代中忽略else部分

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!!")

正如 user2357112 提到的,以及 Python 文档中所述 here

a loop’s else clause runs when no break occurs

您可以按照以下方式尝试:

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!!")