【发布时间】:2017-08-09 08:53:34
【问题描述】:
Python 新手。在一个 while 循环中,我要求用户输入一个输入,该输入是一个 dict 的键。然后打印该键的值。这个过程应该继续,直到输入与字典中的任何键都不匹配。我正在使用 if 语句来查看密钥是否在字典中。如果不是,我喜欢 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 有“in”运算符,用于检查序列、字符串、元组等中的成员资格。例如,您可以在此链接中查看:tutorialspoint.com/python/membership_operators_example.htm
标签: python-2.7 while-loop user-input