【问题标题】:Python Breaking a While Loop with user inputPython用用户输入打破一个While循环
【发布时间】: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

【问题讨论】:

标签: python-2.7 while-loop user-input


【解决方案1】:

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

【讨论】:

  • 太棒了!非常感谢。我总是对 python 如此接近英语感到惊讶
  • 我的荣幸!如果此处的答案解决了您的问题,如果您不介意,请将其标记为已接受:)
猜你喜欢
  • 1970-01-01
  • 2019-08-24
  • 2020-10-21
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2020-02-15
  • 1970-01-01
相关资源
最近更新 更多