PYTHON需要为非整数和整数打印错误消息

时间:2016-12-10 02:08:40

标签: python

当我在输入一个整数(例如4,5,6,100等)后在python中运行以下代码时,它会打印"ERROR: the choice can only be 1, 2, or 3." message.

但是,如果我输入一封类似于' xyz'我得到以下内容:

builtins.ValueError: invalid literal for int() with base 10: 'x'

我需要的是在输入ANYTHING但输入1,2或3时显示错误消息,我无法弄清楚如何做到这一点。感谢。

print('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors: ')
choice2 = int(input())
while choice2 != 1 and choice2 != 2 and choice2 != 3:
   print("ERROR: the choice can only be 1, 2, or 3.")
   choice2 = int(input("Please enter a correct choice: "))

2 个答案:

答案 0 :(得分:2)

choice2变量保留为str,如下所示:

choice2 = input()
while choice2 != "1" and choice2 != "2" and choice2 != "3":
    print("Error ...")
    choice2 = input("Please ...")

然后,如果你需要它是int,你可以转换它:

choice2 = int(choice2)

除了:不要使用!=测试每个值,请尝试not in,如下所示:

while choice2 not in ["1", "2", "3"]:
    ...

答案 1 :(得分:1)

您还可以使用try ... except块编辑代码:

choice2 = 0
while 1:
    try:
        choice2 = int(input('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors: '))
        if choice2 == 1 or choice2 == 2 or choice2 == 3:
            break
        else:
            print("ERROR: the choice can only be 1, 2, or 3.")
    except Exception:
        print("ERROR: the choice must be an integer between 1 and 3.")

print("You entered: ", choice2)