Best method for a menu in a command line program?

MRAB python at mrabarnett.plus.com
Thu Nov 4 03:13:25 CET 2010


On 04/11/2010 01:19, braden faulkner 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?
>
Here's an alternative:

def option_c():
     temp = input("Celsius temperature:")
     print "Fahrenheit:", celsius_to_fahrenheit(temp)

def option_f():
     temp = input("Fahrenheit temperature:")
     print "Celsius:", fahrenheit_to_celsius(temp)

options = {"c": option_c, "f": option_f}
while True:
     choice = raw_input("option:")
     if choice == "q":
         break
     options.get(choice, print_options)()



More information about the Python-list mailing list