Handling text menu in Python
- by PulpFiction
Hi all.
I am trying to create a text based menu in Python.
Here is the code:
#!/usr/bin/env python
def testcaseOutput():
print '1. Add. 2. Subtract. 3. Divide. 4. Multiply'
try:
answer = int(raw_input('Enter a value (1 - 4) >. '))
except ValueError:
print 'Invalid input. Enter a value between 1 -4 .'
testcaseOutput()
if answer in range(1, 5):
return answer
else:
print 'Invalid input. Enter a value between 1 - 4.'
testcaseOutput()
My question:
When the user enters an invalid input, i.e. not a number, I want this function to get called again. So I used the recursive approach which I think is bad design. I use that approach again in the
if answer in range(1, 5).
Is there any other way to handle this? I need the prompt called again when there is an invalid input.
Also, is there any way I can club the two constraints: check whether input is a number and check whether the number is in the range(1,5) together? As you can see, I am checking that individually.