Best method for a menu in a command line program?

Tim Harig usernet at ilthio.net
Wed Nov 3 22:19:23 EDT 2010


On 2010-11-04, braden faulkner <brf256 at gmail.com> wrote:
> I'm using a menu for my command line app using this method.
>
> choice = "foobar"
> while choice != "q":
>     if choice == "c":
>         temp = input("Celsius temperature:")
>         print "Fahrenheit:",celsius_to_fahrenheit(temp)
>     elif choice == "f":
>         temp = input("Fahrenheit temperature:")
>         print "Celsius:",fahrenheit_to_celsius(temp)
>     elif choice != "q":
>         print_options()
>     choice = raw_input("option:")
>
> Just wondering if there is another or more efficient way I should be doing it?

You are looking for a dictionary with function references maybe?

menu_options = {
	'c':io_celsius_to_fahrenheit,
	'f':io_fahrenheit_to_celsisus,
	'q':print_options
}

The io versions of the functions would wrap the conversion functions to get
the input and print the output.

choice = "foobar"
while choice != 'q':
	try:
		menu_options[choice]()
	except KeyError:
		# else code here
	choice = raw_input("option:")



More information about the Python-list mailing list