2017-03-17 157 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

我的荣幸!如果这里的答案解决了您的问题,请将它标记为已接受,如果您不介意:) –