Python Forum

Full Version: Menu Choice Selection not Working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Morning all. Hope you are all well.

So I have recently started to learn python and i am a bit stuck.

I am working on a simple menu but for some reason, it just keeps looking even if i choose the option to quit (option 3).

Anyone able to tell me what I am doing wrong please? (Sorry i tried to use code snippet, but didn't work, hence "quote" instead, and hence the missing indentation)

choice = "0"

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 menuChoice



while choice != 3 :

	choice = mainMenuChoice()

	if choice == 1:
		print("You chose option 1")

	elif choice == 2:
		print("You chose option 2")

quit()

Image attached...
Ok i found it... I need to convert the return value to an integer as the default is a string value and thus does not recognise the response as a correct value.
I've always preferred using True ina while statement.
Your code modified a little

def main_menu():
    print('\nplease make a selection\n')
    print(", ".join(['1 - Option 1', '2 - Option 2', '3 - Option 3 (Quit)']))

while True:
    main_menu()
    choice = int(input('Make a choice\n>> '))
    if choice == 1:
        print('\nYou chose option 1\n')
    elif choice == 2:
        print('\nYou chose option 2\n')
    elif choice == 3:
        print('\nYou chose option 3.\nGoodbye!')
        break
    else:
        print('Please choose one of the available options.')
output
Output:
please make a selection 1 - Option 1, 2 - Option 2, 3 - Option 3 (Quit) Make a choice >> 2 You chose option 2 please make a selection 1 - Option 1, 2 - Option 2, 3 - Option 3 (Quit) Make a choice >> 1 You chose option 1 please make a selection 1 - Option 1, 2 - Option 2, 3 - Option 3 (Quit) Make a choice >> 3 You chose option 3. Goodbye!
(Nov-21-2022, 10:17 AM)ChLenx79 Wrote: [ -> ]Morning all. Hope you are all well.

So I have recently started to learn python and i am a bit stuck.

I am working on a simple menu but for some reason, it just keeps looking even if i choose the option to quit (option 3).

Anyone able to tell me what I am doing wrong please? (Sorry i tried to use code snippet, but didn't work, hence "quote" instead, and hence the missing indentation)

Maybe a corrected version of your code would be more help than trying to explain what you've done wrong: as the saying goes; a picture is worth a thousand words (or something like that).

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:

    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()
I think that you should be able to see what I've changed and why, but if you can't understand the changes, then feel free to ask.

As a foot note, there is no error checking for the input() but again, if you want that, simply ask, or better still try: (hint hint) and code a checking loop.
That's actually a lot slicker. Thanks both! And thanks for tidying up my post too. Big Grin
Can also look how i do it in this post.
I like designing for reuse. A menu can be implemented primarily as data with just a little code sprinkled in.
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.