循环直到用户输入符合要求

问题描述 投票:0回答:1

我正在和我的儿子一起编写 Python 代码,我们希望用户做出选择(“t”或“d”)才能继续。 由于缺乏 GoTos,我认为使用

while
是个好主意,但我们无法成功编码。

我们的代码:

while (answer != "t" and answer != "d"):
    answer = input(question)

question
是包含问题(惊喜)的变量。 似乎
answer
- 应该保存 while 循环的输入结果 - 从未被设置,因为无论用户输入什么,我都会再次提示。

python while-loop compare
1个回答
0
投票

goto
是过去的爆炸!这是在 Python 中执行此操作的一种方法:

question  = "Enter answer:  "
while True:
    answer = input(question).lower()
    if answer in ["t", "d"]:
        break
# have entered t or d
print(answer)
© www.soinside.com 2019 - 2024. All rights reserved.