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?