在python中请求输入时遇到问题

时间:2014-03-22 22:41:56

标签: python input try-catch handle except

我在python中遇到麻烦的处理输入。我有一个程序,要求用户提供要计算的建议数。他可以输入任何正整数和空白("")。我尝试使用"尝试:,除了:"命令,但后来我忽略了空白输入的可能性。顺便说一句,空白意味着建议将是10。

我尝试使用ascii模块,但我的程序最终完全令人困惑。如果有人能让我了解这个想法或给我一个如何处理这件事的例子,我会很高兴。

我输入的程序是:

while input_ok==False:                                                            
    try:                                                                          
        print "Enter the number of the recommendations you want to be displayed.\
        You can leave blank for the default number of recommendations(10)",          
        number_of_recs=input()                                                    
        input_ok=True                                                             
    except:                                                                       
        input_ok=False  

P.S。只是为了确保thenumber_of_recs,可以是正整数或空白。应忽略字母和负数,因为它们会在程序的其余部分中创建错误或无限循环。

1 个答案:

答案 0 :(得分:0)

while True:
    print ("Enter the number of the recommendations you want to " + 
            "be displayed. You can leave blank for the " + 
            "default number of recommendations(10)"),
    number_of_recs = 10 # we set the default value
    user_input = raw_input()
    if user_input.strip() == '':
        break # we leave default value as it is
    try:
        # we try to convert string from user to int
        # if it fails, ValueError occurs:
        number_of_recs = int(user_input)

        # *we* raise error 'manually' if we don't like value:
        if number_of_recs < 0:
            raise ValueError 
        else:
            break # if value was OK, we break out of the loop
    except ValueError:
        print "You must enter a positive integer"
        continue

print number_of_recs