首页 > 解决方案 > 验证用户输入并执行正确的输入

问题描述

我要求用户输入 1 或 2,如果他们没有输入有效的响应,我会再次提示输入。但是,当我运行此代码时,如果输入无效,它会再次提示它们,但如果它们的新输入有效,它会继续再次提示它们,而不是执行正确输入的代码。

userInputB = int(input("Enter '1' if you would like to get out of bed, or '2' if you would like to sleep in: "))
    while True:
        if userInputB == 1:
            print("Great! Let's move on.")
            break
        elif userInputB == 2:
            print("Okay. You have decided to sleep in for five more minutes.")
            for i in range(5,0,-1):
                print(i,'...')
            break
        while userInputB != 1 or userInputB != 2:
            print("Invalid Response.") 
            userInputB = int(input("Enter '1' if you would like to get out of bed, or '2' if you would like to sleep in: "))

标签: python

解决方案


这一行是错误的:

while userInputB != 1 or userInputB != 2:

更改为 ( AND):

while userInputB != 1 and userInputB != 2:

你的代码将是fine.


推荐阅读