Python Bibliotheca
Python resources for teachers and students.

Using dictionaries for program menus

Python's dictionaries are a handy way to create menus for use in your programs. The following program does nothing very sophisticated. It simply takes a word as input and prints it either forward or backward depending on the menu choice. Notice also the use of the try-except statements to handle the program exit and invalid input.

import string

def printForward(word):
    for chr in word:
        print string.upper(chr),
    print

def printBackward(word):
    for i in range(len(word)-1, -1, -1): # count backward from the end of word
        print string.upper(word[i]),
    print

def main():
    menu = {'F': printForward,
            'B': printBackward}
    while 1:
        try:
            word = raw_input("Type a word (Ctrl-D to quit): ")
        except EOFError:
            print "Bye."
            break
        prompt = "Print '%s' (F)orward or (B)ackward? " % word
        choice = string.upper(raw_input(prompt))
        try:
            menu[choice](word)
        except KeyError:
            print "'%s' is not a valid option. Try again." % choice

if __name__ == '__main__':
    main()

Running the program looks like this:

Type a word (Ctrl-D to quit): sibley
Print 'sibley' (F)orward or (B)ackward? f
S I B L E Y
Type a word (Ctrl-D to quit): warriors

Print 'warriors' (F)orward or (B)ackward? b
S R O I R R A W
Type a word (Ctrl-D to quit): 
Bye.

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster