python - 如何在Python中返回到前一部分代码?

标签 python python-3.x command-line-interface

我正在开发 CLI 应用程序并使用 PyInquirer创建一个选择菜单。所以我创建的是一个选择菜单,它要求用户选择要做什么,选项是:

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

我创建了一个功能,当您选择查看任务时,它会提示另一组选择。然而,从这里我想返回主菜单。我似乎无法理解我需要这样做的逻辑。我知道我可以对所有可能的路径进行硬编码,但必须有更好的方法来做到这一点。我考虑过创建函数,但我能想到的唯一方法是互相调用,这是行不通的。

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

感谢您的指导或建议。

最佳答案

您可以将整个内容包装在 while True: 语句中,这样每当您完成任何路径时,您都会返回到主菜单选择。当你想退出时,只需使用break退出循环即可。下面是一个简单的示例。

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

关于python - 如何在Python中返回到前一部分代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913642/

相关文章:

python - 当用户提交某些内容时返回实例属性

python - Django - 外键约束的独特集合

python-3.x - 如何检查 Pandas 单元格值是否为 nan

Python:有效地在容器中找到重复项

json - 如何将文件夹组织的 .json 文件合并到单个 JSON 文件中,并以文件夹/文件名作为键

linux - 如何清理 bash 中分隔符也在双引号内的 csv?

python - 为什么我的位置查找功能出现值错误?

Python:线程无故停止

python - 如何使用 Orange 离散化存储在 numpy 数组中的数据?

php - PHP exec() 返回值是什么?