开发者

Handling text menu in Python

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 calle开发者_如何学JAVAd 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.


One possible refactoring is to use a loop, that continues to print the instructions and read input until acceptable input has been given:

def testcaseOutput():
    while True:
       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 .'
           continue

      if not answer in range(1, 5):
          print 'Invalid input. Enter a value between 1 - 4.'
          continue

      return answer


def testcaseOutput():

    answer = None
    legal_answers = ['1','2','3','4']
    tried = False
    while answer not in legal_answers:
        print "%s1. Add. 2. Subtract. 3. Divide. 4. Multiply" % \ 
              "Invalid input. " if tried else ""
        answer = raw_input('Enter a value (1 - 4) >. ')
        tried = True

    return answer #int(answer) if you really do want integers


Place the entire body of the function in a while True: loop (removing the recursive call, of course).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜