2017-03-17 105 views
0

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 
+0

作爲@christopher曾建議我也會建議一樣,Python有「中」經營者,這是用來按順序檢查會員,字符串,元組etcetra。你可以在這個鏈接檢查例子:https://www.tutorialspoint.com/python/membership_operators_example.htm –

回答

0

choice == choice將永遠如此。你真正想要做的是檢查choice是否在Animal_list。嘗試改變這樣:

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 in Animal_list: 
     print "%s is a %s" % (choice, Animal_list[choice]) 
    else: 
     break 
+0

太棒了!非常感謝你。我總是驚訝蟒蛇是如此接近英語 –

+0

我的榮幸!如果這裏的答案解決了您的問題,請將它標記爲已接受,如果您不介意:) –