Pages

Python: Usign Dictionary For Menu

Using dictionary for menus are no so popular nowadays because of visual programing enviroment. But it is good to know.


def right():
print "\nYou turned right and see the beautiful lady.\n"

def left():
print "\nYou turned left and see the witch.\n"

def stand():
print "\nYou decided to do nothing. So, a thunder hit you!..\n"

print "What is your choice?"
print " 1 : Go right"
print " 2 : Go left"
print " 3 : Stand still"

choice = input('Select what to do:>')

menu = { 1 : right ,
2 : left ,
3 : stand
}
 
menu[choice]()

As you see, we are getting value with key (choice). This returns another word(right, left, stand). Brackets complete the function name. So we call our function as result.

right()
left()
stand()