Home > Blockchain >  How can I implement a working return function in Python
How can I implement a working return function in Python

Time:11-26

So basically, I have a main menu function. The user makes a choice in this menu which is tied to a variable. The main menu function then calls that function. The user chooses a product and its amount there.

So it works until here.

Then after the user enters everything, I want the user to stay in that main menu until they choose to return to the main menu which is represented by the choice variable.

def main_menu(choice=0):
    while True:
        choice = int(input(“Make a choice: “))
        if choice==1:
            dishes()
        if choice==2:
            desserts()
        if choice==3:
            break

def dishes(choice=0):
    print(“1) Buy a dish”)
    print(“2) Go to main menu”)
    choice = int(input(“Make a choice: “))

    if choice==1:
        # Select which dish to buy
        # Select product amount etc.
    if choice==2:
        return choice

def desserts(choice=0):
    print(“1) Buy a dish”)
    print(“2) Go to main menu”)
    choice = int(input(“Make a choice: “))

    if choice==1:
        # Select which dish to buy
        # Select product amount etc.
    if choice==2:
        return choice

main_menu(choice)

I don’t want to create a recursion because I cannot terminate the program when I do that. I want to first call a function from the main menu. Then the function should return a value to the main menu but should not call itself again. The main menu function should continue calling that function until the user decides not to. How do I make this work?

CodePudding user response:

I would refactor the submenus into a while loop:

def dishes():
    while True:
        print(“1) Buy a dish”)
        print(“2) Go to main menu”)
        choice = int(input(“Make a choice: “))

        if choice==1:
            # Select which dish to buy
            # Select product amount etc.
        if choice==2:
            break

    return # return a value if that's part of the program

Also, I notice that the quotes are "smart" quotes, which python doesn't recognize as regular quotes (not sure if that's just a copy/paste issue with Stack Overflow).

  • Related