简体   繁体   中英

How to go back to a previous part of the code in Python?

I am working on a CLI application and using PyInquirer to create a select menu. So what I have created is a select menu, which asks the user to choose what to do, the options are:

  1. view task,
  2. Add Task,
  3. Push up Task.

I've created a function that when you select view task, it prompts another set of choices. However, from here I'd like to return back to the main menu. I can't seem to wrap my head around the logic I need to do this. I know I could hard-code all the possible paths but there must be a better way to do this. I thought about creating functions but the only way I could think of them is by calling each other which wouldn't work.

def main():

main_menu_selection = prompt(main_menu, style=custom_style_2)
# Part I reference below
if main_menu_selection['which_task']== 'View Tasks':
    view_tasks_selection = prompt(view_tasks, style=custom_style_2)


if (view_tasks_selection['view_task']).lower() == 'daily':
    print_tasks("daily")
    # Function to return to menu
    print("Press Enter to return to Main Menu")
    user_input = input()
    if user_input:
        main_menu_selection = prompt(main_menu, style=custom_style_2)
        # Here I would need it to go back to the if statement mentioned above

Thank you for any guidance or advice.

You can wrap the whole thing in a while True: statement, so that whenever you've finished with any of the pathways, you return to the main menu select. When you want to quit, just use break to exit out of the loop. Below is a quick example.

def main():

    while True:
        main_menu_selection = prompt(main_menu, style=custom_style_2)

        # Part I reference below
        if main_menu_selection['which_task']== 'View Tasks':
            view_tasks_selection = prompt(view_tasks, style=custom_style_2)


        if (view_tasks_selection['view_task']).lower() == 'daily':
            print_tasks("daily")

        else:
            break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM