Python:检查用户输入猜测任何项目

Python: Checks user input guess any item

我是新手,需要帮助。我要求用户猜测任何项目,如果它不正确 - 继续询问。但是,我尝试了很多方法,但无法获得正确的代码。有时,它只询问 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!')

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

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' 或元素都是唯一的,集合是一种更有效的数据结构。

您的代码将变为:

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!')