Handling text menu in Python

Posted by PulpFiction on Stack Overflow See other posts from Stack Overflow or by PulpFiction
Published on 2010-05-25T09:57:27Z Indexed on 2010/05/25 10:01 UTC
Read the original article Hit count: 143

Filed under:

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.

© Stack Overflow or respective owner

Related posts about python