2013-02-26 56 views
4

Python新手在这里,试图将测验输入限制为数字1,2或3。
如果输入文本,程序崩溃(因为文本输入不被识别)
这里是我所拥有的改编: 任何帮助最受欢迎。将输入限制为仅限整数(文本崩溃PYTHON程序)

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

试试这个,假设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 
+0

我上传了我的整个程序http://temp-share.com/show/f3YguH62n底部的百分比也存在问题,有些人会对此发笑。它旨在向学生展示作为编程的入门介绍 - 我真的需要掌握! – 2013-02-26 21:42:39

+0

@LeecollinsCollins:看看[字符串格式迷你语言](http://docs.python.org/2/library/string.html#format-specification-mini-language),特别是在浮点数格式。这里有一个特定的'%'百分比格式化功能。 – 2013-02-26 21:45:39