如果答案无效,则在循环时重新启动

时间:2019-07-15 00:16:20

标签: python-3.x

我有以下代码,如果其他代码被触发,如何继续让他们再次输入而不是退出循环?

尝试了一些True东西,但无法正常工作。

if awaken in ["a", "stand up"]:
    print("Holy...")
elif awaken in ["b", "take a breath"]:
    print("Just more text holding")
elif awaken in ["c", "go back to sleep"]:
    print("")
else:
    print("I don't understand your answer... try again")

1 个答案:

答案 0 :(得分:0)

将其全部放入while循环中。

while True:
    awaken = input("Enter command: ").strip()  # I presume that you are taking input from user
    if awaken in ["a", "stand up"]:
        print("Holy...")
        break
    elif awaken in ["b", "take a breath"]:
        print("Just more text holding")
        break
    elif awaken in ["c", "go back to sleep"]:
        print("")
        break
    else:
        print("I don't understand your answer... try again")

输出:

Enter command: x
I don't understand your answer... try again
Enter command: y
I don't understand your answer... try again
Enter command: a
Holy...

别忘了使用break

我不确定为什么您的最初不能使用,但是上面的循环应该可以完成工作。