Python 2.7 Python使用用户输入打破While循环

Python 2.7 Python使用用户输入打破While循环,python-2.7,while-loop,user-input,Python 2.7,While Loop,User Input,Python新手。在一个while循环中,我要求用户输入一个dict的键,然后打印该键的值。这个过程应该继续,直到输入与dict中的任何键都不匹配。我正在使用if语句查看该键是否在dict中。如果不是,我希望while循环中断。到目前为止,我还不能让它打破 谢谢大家 Animal_list = { 'lion': 'carnivora', 'bat': 'mammal', 'anaconda': 'reptile', 'salmon': 'fish', 'whale': 'cet

Python新手。在一个while循环中,我要求用户输入一个dict的键,然后打印该键的值。这个过程应该继续,直到输入与dict中的任何键都不匹配。我正在使用if语句查看该键是否在dict中。如果不是,我希望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

choice==choice
将始终为真。您真正想做的是检查
选项
是否在
动物列表
中。尝试更改为:

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

伟大的非常感谢你。我总是很惊讶巨蟒如此接近英语——我很高兴!如果这里的答案解决了您的问题,请在不介意的情况下将其标记为已接受:)我还将建议与@christopher建议的相同,python有“in”操作符,用于检查序列、字符串、元组等的成员资格。例如,您可以在此链接中检查: