在Python中,可以使用一行程序以简单直观的方式设置具有特殊条件(如默认值或条件)的值。
result = 0 or "Does not exist." # "Does not exist."
result = "Found user!" if user in user_list else "User not found."
是否可以编写一个捕捉异常的类似语句?
from json import loads
result = loads('{"value": true}') or "Oh no, explosions occurred!"
# {'value': True}
result = loads(None) or "Oh no, explosions occurred!"
# "Oh no, explosions occurred!" is desired, but a TypeError is raised.
可以在一行中使用exec:
在python中不可能执行单行异常处理语句。我们可以编写一个函数来实现这一点。
示例用法:
支持多个参数
错误捕获过程仍可能被中断:
如果此行为是不需要的,请使用
BaseException
:相关问题 更多 >
编程相关推荐