-1

我有一个for loop循环遍历联系人对象的动态列表,并检查联系人电子邮件是否满足指定条件。当列表用尽时,我使用带有 的else语句for loop返回“抱歉条件未满足”。这种方法可以正常工作,除非列表只有一个满足条件的联系人。在这种情况下,主体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!!")
4

1 回答 1

0

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

循环的 else 子句在没有中断发生时运行

您可以尝试以下方式:

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!!")
于 2017-09-19T20:22:58.873 回答