python - 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()
解决方案
值得注意的是,您的选择分为两类,它们之间有一个重要区别。
一方面,您可以使用break
或return
条件变量来跳出循环,并最终返回给调用者。在这些选项中,我会说只选择提供最干净代码的那个。
另一方面,您可以使用exit()
which 结束程序,然后.
如果您希望将其用作顶级菜单以外的其他内容,例如包装在库中以用作其他内容的子菜单,您不希望程序突然退出。
一般来说,exit()
是相当大的炸药块,应该尊重一点。
推荐阅读
- javascript - 如何使用 ES6 和 Node Js 删除 txt 文件中的重复项?
- c++ - 我该怎么做才能使 clang 正确地将隐式生成的构造函数标记为已删除?
- oracle - PL/SQL 过程不返回任何
- php - 我需要获得 32 位作曲家吗?
- string - 仅当所有原始列表中都存在字符串时,才合并字符串数组列表并传递给新的数组列表
- php - 如何使用多个服务器名称修复连接字符串无效
- android - 在 Android 上为片段着色器使用 3D 纹理
- google-cloud-platform - 优化文件夹子集的 gsutil 下载
- python-3.x - 如何将值从0-20的二维数组存储到python中的灰度图像
- python - 我导入的 .txt 表未与标题正确对齐(Python)