2017-04-08 77 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

相關問題