2017-04-08 51 views
0

此搜索功能有效,但如果我搜索名为Sarah的动物,并且列表中有两个名为Sarah的动物,它只打印其中的一个。我应该如何使它打印所有的搜索匹配?如何打印对象列表中的所有搜索匹配

def search(): 
choice = int(input(""" 
1 Name 
2 Age 
3 Specie 
4 Gender 
What do yo want to search for? """)) 

if choice == 1: 
    your_search = input("Write the animal name: ").capitalize() 
    for Animals in animal_list: 
     if your_search == Animals.name: 
      print(Animals) 
      break 

    else: 
      print("Sorry, couldn't find any animal called " + your_search + ", maybe check the spelling.") 

回答

0

尝试

+0

我试图除去休息时间,而那也打印else语句,即使它在列表中查找搜索的动物。 – Emiki

0

你告诉程序停止搜索找到一个结果后,每个成功匹配后,除去休息。只是删除break命令,并添加标记,如果一个名字,发现他表示:

def search(): 
    choice = int(input(""" 
    1 Name 
    2 Age 
    3 Specie 
    4 Gender 
    What do yo want to search for? """)) 

    if choice == 1: 
     your_search = input("Write the animal name: ").capitalize() 
     found = False 
     for Animals in animal_list: 
      if your_search == Animals.name: 
       found = True 
       print(Animals) 
     if found == False: 
      print("Sorry, couldn't find any animal called " + 
        your_search + ", maybe check the spelling.") 
+0

我已经尝试过,然后它打印搜索匹配,但由于某种原因也是其他语句。 – Emiki

+0

你的其他语句与if语句不在同一行,所以在它仍然要读取else之后。您需要在其他前面添加四个空格,以使其与if语句对齐。 – jss367

+0

但它然后为每个不匹配的动物打印else语句 – Emiki

相关问题