Python新手。在一個while循環中,我要求用戶輸入一個字典的關鍵字。然後打印該鍵的值。這個過程應該繼續下去,直到輸入與字典中的任何鍵不匹配。我使用if語句來查看密鑰是否在字典中。如果不是,我不喜歡while循環打破。到目前爲止,我無法讓它突破。Python用戶輸入打破while循環
謝謝大家
Animal_list = {
'lion': 'carnivora', 'bat': 'mammal', 'anaconda': 'reptile',
'salmon': 'fish', 'whale': 'cetaceans', 'spider': 'arachnida',
'grasshopper': 'insect', 'aligator': 'reptile', 'rat': 'rodents',
'bear': 'mammal', 'frog': 'amphibian', 'turtles': 'testudines'
}
while True:
choice = raw_input("> ")
if choice == choice:
print "%s is a %s" % (choice, Animal_list[choice])
elif choice != choice:
break
作爲@christopher曾建議我也會建議一樣,Python有「中」經營者,這是用來按順序檢查會員,字符串,元組etcetra。你可以在這個鏈接檢查例子:https://www.tutorialspoint.com/python/membership_operators_example.htm –