Nov-23-2022, 05:56 AM
(This post was last modified: Nov-23-2022, 05:56 AM by deanhystad.)
I like designing for reuse. A menu can be implemented primarily as data with just a little code sprinkled in.
def mainMenuChoice():
print("Please make a selection...")
print("")
print("1 - Option One")
print("2 - Option Two")
print("3 - Option Three (Quit)")
return input("Enter your choice: ")
while True:
choice = mainMenuChoice()
if choice == '1':
print("You chose option 1")
elif choice == '2':
print("You chose option 2")
elif choice == '3':
print("You chose option 3")
input("Press the enter key to quit")
quit()
An alternative robust solution is to do the conversion and capture the exception.
def menu(menu_options, menu_keys="ABCDEFGHIJK"): while True: choices = {a:b for a, b in zip(menu_keys, menu_options)} print("\nPlease make a selection") for a, b in choices.items(): print(f"{a} : {b}") choice = input("Enter your choice: ") if choice in choices: menu_options[choices[choice]]() break print(f"{choice} is not a valid selection.") menu_a = { "Option A" : lambda: print("You chose option A"), "Option B" : lambda: print("You chose option B"), "Quit" : lambda : quit("You chose quit") } menu_b = { "Option 1" : lambda: print("You chose option 1"), "Option 2" : lambda: print("You chose option 2"), "Quit" : lambda : quit("You chose quit") } while True: menu(menu_a, "ABC") menu(menu_b, "123")Why do so many programmers insist on converting strings to numbers when they don't need a number? This is rob101's code converted to accept a menu string. The code does not crash no matter what you enter as input (except ctrl+c).
def mainMenuChoice():
print("Please make a selection...")
print("")
print("1 - Option One")
print("2 - Option Two")
print("3 - Option Three (Quit)")
return input("Enter your choice: ")
while True:
choice = mainMenuChoice()
if choice == '1':
print("You chose option 1")
elif choice == '2':
print("You chose option 2")
elif choice == '3':
print("You chose option 3")
input("Press the enter key to quit")
quit()
An alternative robust solution is to do the conversion and capture the exception.
def mainMenuChoice(): print("Please make a selection...") print("") print("1 - Option One") print("2 - Option Two") print("3 - Option Three (Quit)") menuChoice = input("Enter your choice: ") return int(menuChoice) while True: try: choice = mainMenuChoice() if choice == 1: print("You chose option 1") elif choice == 2: print("You chose option 2") elif choice == 3: print("You chose option 3") input("Press the enter key to quit") quit() except ValueError: print("That is not a valid choice")As you can see, converting the user input to an integer doesn't provide any benefit. All it does is make you write code to catch the inevitable ValueError that occurs when someone fat fingers "e" instead of 3. If you don't use the input in an equation or a loop count or some use where the numeric value is important, don't convert it to a number.