限制输入仅限整数(文本崩溃PYTHON程序)

Lee*_*ins 4 python

这里的Python新手,尝试将测验输入限制为仅限1,2或3.
如果键入文本,程序崩溃(因为文本输入无法识别)
这是对我所拥有的改编:欢迎任何帮助.

choice = input("Enter Choice 1,2 or 3:")
if choice == 1:
    print "Your Choice is 1"
elif choice == 2:
    print "Your Choice is 2"  
elif choice == 3:
    print "Your Choice is 3"
elif choice > 3 or choice < 1:
    print "Invalid Option, you needed to type a 1, 2 or 3...."
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

raw_input()改为使用,然后转换为int(捕获ValueError转换失败).您甚至可以包括范围测试,ValueError()如果给定的选择超出允许值范围,则显式提高:

try:
    choice = int(raw_input("Enter choice 1, 2 or 3:"))
    if not (1 <= choice <= 3):
        raise ValueError()
except ValueError:
    print "Invalid Option, you needed to type a 1, 2 or 3...."
else:
    print "Your choice is", choice
Run Code Online (Sandbox Code Playgroud)