Python Forum
Menu Choice Selection not Working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Menu Choice Selection not Working
#1
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.
Larz60+ write Nov-21-2022, 10:45 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Please use bbcode (python) code tags, rather than attachments.

Attached Files

Thumbnail(s)
       
Reply
#2
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!
BliepMonster and ChLenx79 like this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
(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.
ChLenx79 and menator01 like this post
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#4
That's actually a lot slicker. Thanks both! And thanks for tidying up my post too. Big Grin
rob101 likes this post
Reply
#5
Can also look how i do it in this post.
rob101 likes this post
Reply
#6
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  combobox_callback(choice choice part of openfile name (kind of dependency) janeik 9 1,458 Sep-10-2023, 10:27 PM
Last Post: janeik
  Menu selection using function leodavinci1990 8 14,691 Dec-05-2019, 01:48 PM
Last Post: snippsat
  random selection of song and artist not working Unknown_Relic 2 2,355 Nov-08-2019, 02:06 PM
Last Post: perfringo
  webbrowser and menu not working. sik 1 1,839 Oct-31-2019, 03:39 AM
Last Post: newbieAuggie2019
  Simple cli menu quits on selection pamamolf 19 9,611 Oct-26-2017, 02:09 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020