[Tutor] Numbers & Characters As Dictionary Keys

Alan G alan.gauld at freenet.co.uk
Mon Jun 20 10:11:53 CEST 2005

> "raw_input", but I get "H is not defined" when I run the script.  
> Essentially, I'd like the user to enter a number for most items, 
> but use letters for "Help", "Quit", and "Back to Main".

Are you sure? That kind of inconsistent input is one of the 
big no-nos of user interface design. It usually confuses 
the heck out of users!

Hoewever to the problem at hand.
It should just be a case of changing the keys in the dictionary.
Unfortunately you've told us the problem but shown us the code 
that woreks, not the broken copde. So we can only guess what 
you might have done!

But basically here is a sample program that does approximately 
what you want:

def hello(): print 'hello'
def goodbye(): print 'goodbye'

menu = { '1' : ('hello', hello),
         'Q' : ('goodbye', goodbye)}

for m in menu.keys():
   print "%s\t%s" % (m,menu[m][0])

cmd = raw_input('pick one ').upper()

Does that help?

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list