继续询问输入,直到给出正确的答案(Python)(非数值)

时间:2015-12-01 05:40:51

标签: python

我尝试编写一段代码,然后重复问题,直到给出正确的答案,并对可能的答案做出一些不同的回答。这是我到目前为止所做的,但在它响应给定的输入之后,程序继续前进。我无法弄清楚如何使用while循环执行此操作,因为它以特定答案结束而不是以其他方式结束。

answer = input("What is your favorite eldest daughter's name?   ").lower()

if answer == "a" or answer == "al":
    print("Of course, we all knew that")
elif answer == "c" or answer == "chris":
    print("""Oh she must be standing right there.
But that\'s not it, try again.""")

elif answer == "e" or answer == "ed":
    print("Not even the right gender. Try again.")
elif answer == "n" or answer == "nic":
    print("Only biological children please.")

else:
    print("I'm sorry. Only children. Were you thinking of the dogs?")

3 个答案:

答案 0 :(得分:1)

ng-repeat就是你想要的。像这样使用它:

break

答案 1 :(得分:1)

你基本上需要不断重复这个问题,直到程序认为答案可以接受为止。

代码

#!/usr/bin/python3 -B

answers = ['alice', 'chris', 'bob']
answer  = None
while answer not in answers:
    answer = input('Enter your answer: ')

print('Your answer was: {}'.format(answer))

此处的代码基本上都有一个可接受的answers列表,并将用户的answer初始化为None。然后它进入while循环,该循环不断重复,直到在可接受的answer列表中找到用户的answers

输出

➜  ~  ./script.py
Enter your answer: alice
Your answer was: alice
➜  ~  ./script.py
Enter your answer: no
Enter your answer: no
Enter your answer: yes
Enter your answer: bob
Your answer was: bob

改进守则

您现在可以调整代码以使用您选择的消息。另请注意,如果要为任何可接受的条目提供不同的响应,可以使用字典并稍微更新代码。

例如,你可以这样:

answers = {
    'bob': 'This was the best choice',
    'alice': 'Everyone picks the hot gal',
    # ... and so on
}

然后,您可以通过查看answers字典的(例如while answer not in answers.keys():)继续进行迭代。

当循环以可接受的answer退出时,您只需

print(answers[answer])

如果answers == 'alice',则程序会打印Everyone picks the hot gal

它可以显着简化您的代码,让您更容易理解和使用:)

答案 2 :(得分:0)

使用while循环和break语句:

while True:
    # . . .
    if correct_answer:
        break