[Tutor] Just a newbie question...

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 21 Feb 2002 18:36:04 +0100


On  0, Sean 'Shaleh' Perry <shalehperry@attbi.com> wrote:
> > 
> > Also, is there a nice way to change this lousy code below?  I want to change
> > it like a "switch" conditional statement in C, to display a "menu-like"
> > choices.  What is a good alternative to "switch" of C in Python?  And what is
> > a "good terminator" if I press "Q or q" in Python?
> > 
> 
> menu = {1: fib, 2: mtable}
> 
> choice = raw_input("Enter a choice: ")
> func = menu[choice]
> func()
> 
> What this does is make a dictionary (hash table) where each choice is a key and
> the value of the key is a function to run.

A problem: 1 and 2 in your menu dictionary are integers, but raw_input()
returns a string.

Either do

menu = {"1": fib, "2": mtable}

or 

choice = int(raw_input("Enter a choice:"))

Also you need to check if the choice actually exists (with
menu.has_key(choice), for instance).

-- 
Remco Gerlich