Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果出现错误,执行此操作并返回,否则在一行中继续执行_Python_Python 3.x - Fatal编程技术网

Python 如果出现错误,执行此操作并返回,否则在一行中继续执行

Python 如果出现错误,执行此操作并返回,否则在一行中继续执行,python,python-3.x,Python,Python 3.x,我的代码中有很多重复,如以下代码块: if err: print('Could not parse text!') print('Error code={}'.format(err.code)) print('Error message={}'.format(err.message)) return err.code 我想让它看起来更好,也许只需要一行代码 因此,我想命令编译器在一行中执行此操作: 如果出现错误,请打印必要的信息并返回错误代码,否则继续执行。 大

我的代码中有很多重复,如以下代码块:

if err:
    print('Could not parse text!')
    print('Error code={}'.format(err.code))
    print('Error message={}'.format(err.message))
    return err.code
我想让它看起来更好,也许只需要一行代码

因此,我想命令编译器在一行中执行此操作:

如果出现错误,请打印必要的信息并返回错误代码,否则继续执行。

大概是这样的:

def error_output(err, text):
    print(text)
    print('Error code={}'.format(err.code))
    print('Error message={}'.format(err.message))
    return err.code

return_if(err, error_output, 'Parse error')
我试过这个:

return error_output(err,'parse error') if err else continue
但是当然不能像这样使用
继续

怎么样:

if err: return error_output(err, 'parse error') 
# more code here

这对于某些度量标准来说是可以接受的,尽管这是一个非常小的代码,但我的目的是想知道是否有一种方法可以阻止带有条件的返回。
return
是一个语句。不能将其转换为表达式。它必须返回。您可以创建一个
raise\u if
函数,在该函数中,它会引发一个给定的异常,以便更高级别地捕获。在Python中,异常通常是处理错误条件的正确方法,因此,如果您被一些基于错误代码的API所困扰,那么将错误代码转换为异常将隐藏错误代码返回的丑陋性,而不让其他代码看到。@RamazanPolat,您要求在一行代码中完成此操作(大概是为了最大限度地减少垂直代码空间的要求,我很理解)-这个答案正好提供了。@MikeMüller“它必须返回”是我一直在寻找的答案。