首页 > 解决方案 > Python 菜单上的 exit()、条件、返回或中断?

问题描述

如果我们在 python 上做一个菜单并且用户选择完成交互的选项。最好使用 exit()、条件、return 还是 break?

带break的例子,我们用break停止无限循环:

def show_menu():
    print('1. Pet kitten\n'
          '0. Exit')


def start_app():
    while True:
        show_menu()
        user_choice = input('Select an option: ')
        if user_choice == '1':
            pet()
        elif user_choice == '0':
            print('\nBye!')
            break
        else:
            print('\nPlease select a number from the menu.')


start_app()

以 exit() 为例,我们使用内置函数 exit() 来停止脚本的执行:

def show_menu():
    print('1. Pet kitten\n'
          '0. Exit')


def start_app():
    while True:
        show_menu()
        user_choice = input('Select an option: ')
        if user_choice == '1':
            pet()
        elif user_choice == '0':
            print('\nBye!')
            exit()
        else:
            print('\nPlease select a number from the menu.')


start_app()

带有条件的示例,当条件改变时 while 停止:

def show_menu():
    print('1. Pet kitten\n'
          '0. Exit')


def start_app():
    continue_ = True
    while continue_:
        show_menu()
        user_choice = input('Select an option: ')
        if user_choice == '1':
            pet()
        elif user_choice == '0':
            print('\nBye!')
            continue_ = False
        else:
            print('\nPlease select a number from the menu.')


start_app()

返回示例,我们完成交互返回一个随机值:

def show_menu():
    print('1. Pet kitten\n'
          '0. Exit')


def start_app():
    continue_ = True
    while continue_:
        show_menu()
        user_choice = input('Select an option: ')
        if user_choice == '1':
            pet()
        elif user_choice == '0':
            print('\nBye!')
            return None
        else:
            print('\nPlease select a number from the menu.')


start_app()

标签: pythonmenureturnexitbreak

解决方案


值得注意的是,您的选择分为两类,它们之间有一个重要区别。

一方面,您可以使用breakreturn条件变量来跳出循环,并最终返回给调用者。在这些选项中,我会说只选择提供最干净代码的那个。

另一方面,您可以使用exit() which 结束程序,然后.

如果您希望将其用作顶级菜单以外的其他内容,例如包装在库中以用作其他内容的子菜单,您不希望程序突然退出。

一般来说,exit()是相当大的炸药块,应该尊重一点。


推荐阅读