首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用用户输入中断While循环的Python

用用户输入中断While循环的Python
EN

Stack Overflow用户
提问于 2017-03-17 17:19:16
回答 1查看 882关注 0票数 0

新来的Python。在which循环中,我向用户请求输入,这是dict的一个键。然后打印那个键的值。此过程应继续进行,直到输入与dict中的任何键不匹配为止。我正在使用if语句来查看键是否在数据块中。如果不是的话,我喜欢让while循环中断。到目前为止我还没能把它弄坏。

谢谢大家

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-17 17:21:51

choice == choice永远是真的。您真正想做的是检查choice是否在Animal_list中。试着改变如下:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42863609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档