【问题标题】:Python: Checks user input guess any itemPython:检查用户输入猜测任何项目
【发布时间】:2021-01-04 23:03:41
【问题描述】:

我是新手,我需要帮助,请。我要求用户猜测任何项目,如果它不正确 - 不断询问。但是,我正在尝试做很多方法,但无法正确编写代码。有时,即使用户输入错误,也只是询问 1 次并停止;或者它不知道答案是对是错,继续问。 谢谢!

animal = ['bird','dog','cat','fish']
while True:
    guess = input('Guess my favorite animal: ')
    if guess == animal:
        print("You are right")
        break
    print('Try again!')

【问题讨论】:

  • if guess in animal:

标签: python if-statement while-loop break


【解决方案1】:

您的代码不起作用,因为您将用户输入与列表进行比较。

guess == animal

将被评估为:

guess == ['bird','dog','cat','fish']   # Evaluates to "false"

测试一个元素是否在列表中很简单:

# A set of animals
animals = ['bird','dog','cat','fish']

'bird' in animals  # Returns True, because bird is in the list
>>> True

'cow' in animals   # Returns False, because cow is not in the list
>>> False

假设列表中的每个“动物”或元素都是唯一的,那么使用集合是一种更有效的数据结构。

然后你的代码变成:

animal = {'bird','dog','cat','fish'}
while True:
    guess = input('Guess my favorite animal: ')
    if guess in animal:
        print("You are right")
        break
    print('Try again!')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-18
    • 2018-11-05
    • 1970-01-01
    • 2022-10-07
    • 2021-12-17
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多