Python:检查用户输入是否有任何项目

问题描述

我是新手,请帮忙。我要用户猜测任何项目,如果它不正确-会不断询问。但是,我正在尝试做很多事情,但是无法正确执行代码。有时,即使用户输入错误,也只问1次就停下来。或它无法识别答案是对还是错并继续询问。 谢谢!

fetch next

解决方法

您的代码无效,因为您正在将用户输入与列表进行比较。

guess == animal

将被评估为:

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

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

# A set of animals
animals = ['bird','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','fish'}
while True:
    guess = input('Guess my favorite animal: ')
    if guess in animal:
        print("You are right")
        break
    print('Try again!')