?
Solved

menu driven

Posted on 2005-04-22
2
Medium Priority
?
294 Views
Last Modified: 2010-04-16
hi i am creating a menu and when the user hits the keys, 1, 2 it does the following functions .....

1. Search
2. Exit

option = raw_input("Enter Your Option: ")

   optfunc = {

      '1': search(),
      '2': exit()
   }
   optfunc[option]()

it doesn't seem to work when i hit 1 or 2. Can anyone help thanks.
0
Comment
Question by:darrenteo82
2 Comments
 

Author Comment

by:darrenteo82
ID: 13840786
the exit function is

def exit():
   sys.exit()
0
 
LVL 14

Accepted Solution

by:
RichieHindle earned 200 total points
ID: 13841016
The code:

   optfunc = {
      '1': search(),
      '2': exit()
   }

actually calls the search and exit functions as it constructs the dictionary, and stores the result of calling the function in the dictionary (and of course sys,exit() never returns).  You need to omit the parentheses:

   optfunc = {
      '1': search,
      '2': exit
   }

This way, you're just referring to the functions rather than calling them.  Your line:

   optfunc[option]()

will then call the appropriate function as you expect.  Here's a full working example:

def search():
    print "search"

def exit():
    print "exit"

option = raw_input("Enter Your Option: ")

optfunc = {

      '1': search,
      '2': exit
   }

optfunc[option]()

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question