At various points in my text-based programs, I've had to write a function for use in multiple-choice menus. It needs to have the following qualities:

  • Ignores non-number input, repeating the request if it is given a string.
  • Can be given upper and lower limits on the acceptable numbers, repeating the request if the number the user enters is outside these limits.
  • Either or both limits must support being given the value False, in which case that limit will not be applied.

I already have a bit of code for this, but I hate its sheer ugliness and clumsiness. Here it is:

def getChoice(bottom,cap):
    testOne = False
    testTwo = False 
    while testOne == False or testTwo == False:
        
        choice = raw_input()
        
        try:
            choice = int(choice)
            testOne = True
        except:
            print "Please give a valid answer."
            testOne = False

        if (testOne == True):
            if ((choice < bottom) and (bottom != False)) or ((choice > cap) and (cap != False)) or (choice != round(choice)):
                print "Please give a valid answer."
                testTwo = False
            else:
                testTwo = True

    return choice

I'm not even sure if it's bug-free. Anyone able to suggest improvements or better implementations?

Hi,

I'm just starting with Python, so I took your question like an exercise...here is what I did:

def getChoice(bottom = False,cap = False):

    if (bottom and cap) and (bottom > cap): #invalid args
        raise 1 
    
    msg = 'Enter a number'
    
    if bottom:
        msg += ' greater than ' + str(bottom)
    if cap:
        msg += ' smaller than ' + str(cap)


    choice = False
    
    while choice is False :
    
        choice = raw_input(msg+'>')    
        
        try:
            choice = int(choice)#int raises an exception if number is like 11.2
            if ((bottom != False) and (choice < bottom)) or ((cap != False) and (choice > cap)):
                raise 1
        except:
            choice = False
            print "Please give a valid answer."
  
    return choice

if __name__ == '__main__':
    print getChoice(14,18)

Regards,
Tudor

Nothing radical - basically worked on your original code:

def getChoice(bottom=False, cap=False):
    while True:
        try:
            choice = int(raw_input("Please enter your choice: "))
            if ((bottom != False) and (choice <= bottom)):
                print "Choice should be greater than", bottom
                continue
            if ((cap != False) and (choice >= cap)):
                print "Choice should be less than", cap
                continue
            return choice
        except ValueError:
            print "Please input intger."
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.