Search code examples
pythoninputtry-catchhandleexcept

Having trouble requesting input in python


i have troubling handling input in python. I have a program that request from the user the number of recommendations to be calculated.He can enter any positive integer and blank(""). I tried using the "try: , except: " commands,but then i leave out the possibility of blank input. By the way blank means that the recommendations are going to be 10.

I tried using the ascii module,but my program ends up being completely confusing. I would be glad if anyone could get me on the idea or give me an example of how to handle this matter.

My program for this input is :

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. Just to make sure thenumber_of_recs , can either be positive integer or blank. Letters and negative numbers should be ignored cause they create errors or infinite loops in the rest of the program.


Solution

  • 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