限制输入为整数(文本导致PYTHON程序崩溃)

4 投票
2 回答
19179 浏览
提问于 2025-04-17 17:14

我是个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...."

2 个回答

2

试试这个,假设 choice 是一个字符串,因为从问题描述来看,它似乎确实是字符串:

if int(choice) in (1, 2, 3):
    print "Your Choice is " + choice
else:
    print "Invalid Option, you needed to type a 1, 2 or 3...."
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

撰写回答