新来的Python。在which循环中,我向用户请求输入,这是dict的一个键。然后打印那个键的值。此过程应继续进行,直到输入与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发布于 2017-03-17 17:21:51
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:
breakhttps://stackoverflow.com/questions/42863609
复制相似问题