In one of my programs I made a more complex way of choosing options.
It involves each option being linked to a particular function.
Imagine I wanted a user to choose one of these functions:
def Quit():
print "goodbye"
os._exit(1)
def say_hello():
print "Hello world!"
def etcetera():
pass
I make a dictionary with key the being user-input keyword, and values being a description and a function. In this case I use string numbers
OPTIONS = {"0":dict( desc = "Quit", func = Quit),
"1":dict( desc = "Print hello", func = say_hello),
"2":dict( desc = "Another example", func = etcetera)}
Then my menu function looks like this!
def main_menu():
while True:
print "\nPlease choose an option:"
for key in sorted(OPTIONS.keys()):
print "\t" + key + "\t" + OPTIONS[key]["desc"]
input = raw_input("Selection: ")
if not input in OPTIONS.keys():
print "Invalid selection"
else:
OPTIONS[input]["func"]()
>>>main_menu()
Please choose an option
0 Quit
1 Print hello
2 Another example
Selection: 1
Hello world!
Please choose an option
0 Quit
1 Print hello
2 Another example
Selection: 0
goodbye
>>>
EDIT
Alternatively you could make a return keyword such that you could have nested menus.
OPTIONS = {"0":dict( desc = "Quit", func = Quit),
"1":dict( desc = "Go to menu 2", func = menu_2),
OPTIONS2 = {"1":dict( desc = "Another example", func = etcetera)}
def main_menu():
while True:
print "\nPlease choose an option:"
for key in sorted(OPTIONS.keys()):
print "\t" + key + "\t" + OPTIONS[key]["desc"]
input = raw_input("Selection: ")
if not input in OPTIONS.keys():
print "Invalid selection"
else:
OPTIONS[input]["func"]()
def main_2():
while True:
print "\nPlease choose an option :"
print "\t0\tReturn"
for key in sorted(OPTIONS2.keys()):
print "\t" + key + "\t" + OPTIONS2[key]["desc"]
input = raw_input("Selection: ")
if input == '0':
return
if not input in OPTIONS2.keys():
print "Invalid selection"
else:
OPTIONS2[input]["func"]()
>>>main_menu()
Please choose an option
0 Quit
1 Go to menu 2
Selection: 1
Please choose an option
0 Return
1 Another example
Selection: 0
Please choose an option
0 Quit
1 Go to menu 2
Selection: 0
goodbye
>>>