Menu

From Rosetta Code
Revision as of 18:27, 3 June 2009 by rosettacode>Paddy3118 (New task and Python solution)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Menu
You are encouraged to solve this task according to the task description, using any language you may know.

Given a list containing a number of strings of which one is to be selected and a prompt string, create a function that:

  • Print a textual menu formatted as an index value followed by its corresponding string for each item in the list.
  • Prompt the user to enter a number.
  • return the string corresponding to the index number.

The function should reject out-of-range indices by recreating the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the four phrases: 'fee fie', 'huff and puff', 'mirror mirror' and 'tick tock' in a list.

Note: This task is fashioned after the action of the [Bash select statement].

Python

<lang python>def _menu(items):

   for indexitem in enumerate(items):
       print ("  %2i) %s" % indexitem)

def _ok(reply, itemcount):

   try:
       n = int(reply)
       return 0 <= n < itemcount
   except:
       return False
   

def selector(items, prompt):

   'Prompt to select an item from the items'
   if not items: return 
   reply = -1
   itemcount = len(items)
   while not _ok(reply, itemcount):
       _menu(items)
       # Use input instead of raw_input for Python 3.x
       reply = raw_input(prompt).strip()
   return items[int(reply)]

if __name__ == '__main__':

   items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock']
   item = selector(items, 'Which is from the three pigs: ')
   print ("You chose: " + item)

</lang>

Sample runs:

   0) fee fie
   1) huff and puff
   2) mirror mirror
   3) tick tock
Which is from the three pigs:  -1
   0) fee fie
   1) huff and puff
   2) mirror mirror
   3) tick tock
Which is from the three pigs:      0
You chose: fee fie
>>> ================================ RESTART ================================
>>> 
   0) fee fie
   1) huff and puff
   2) mirror mirror
   3) tick tock
Which is from the three pigs: 4
   0) fee fie
   1) huff and puff
   2) mirror mirror
   3) tick tock
Which is from the three pigs: 3
You chose: tick tock