在认为有效之前,如何继续询问用户输入?

时间:2015-10-03 22:26:33

标签: python python-3.x

我的代码旨在要求用户选择首选的家畜。答案应该是“cats”“dogs”

household_animal = (input("Which household animal do you prefer?"))
if household_animal in ("cat", "dog"):
    print("Thanks for your input on which household animal you prefer!")
else:
    print("This is not a household animal, please pick again.")

我不确定如何让程序继续询问输入,直到用户选择“cat”“dog”。如果检测到正确的输入,则不应再要求更多输入。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您需要使用循环迭代

household_animal = input("Which household animal do you prefer?")
while household_animal not in ("cat", "dog"):
    print("This is not a household animal, please pick again.")
    # pick again
    household_animal = input("Which household animal do you prefer?")
print("Thanks for your input on which household animal you prefer!")

答案 1 :(得分:1)

<强>解释

由于在选择合适的动物之前你需要继续询问输入,你应该引入某种形式的循环,直到满足这个条件。

有很多方法可以编写这样的功能,但您正在寻找的是如下所示。

household_animal = None
while household_animal not in ("cat", "dog"):
    if household_animal is not None:
      print ("This is not a household animal, please pick again.")

    household_animal = input ("Which household animal do you prefer?")

print ("Thanks for your input on which household animal you prefer!")
  

注意:代码将循环直到household_animal"cat""dog",并显示错误消息如果用户写了一些不是两者之一的东西。