在函数结束(例如,检查失败)之前,在python中退出函数(没有返回值)的最佳方法是什么?

问题:在函数结束(例如,检查失败)之前,在python中退出函数(没有返回值)的最佳方法是什么?

让我们假设一个迭代,其中我们调用一个没有返回值的函数。我认为我的程序应该表现的方式在以下伪代码中进行了解释:

for element in some_list:
    foo(element)

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return None
    do much much more...

如果我在python中实现此功能,则该函数返回一个None。是否有更好的方式“如果在函数主体中检查失败,则退出没有返回值的函数”?

Let’s assume an iteration in which we call a function without a return value. The way I think my program should behave is explained in this pseudocode:

for element in some_list:
    foo(element)

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return None
    do much much more...

If I implement this in python, it bothers me, that the function returns a None. Is there a better way for “exiting a function, that has no return value, if a check fails in the body of the function”?


回答 0

您可以简单地使用

return

与…完全相同

return None

None如果执行到达函数主体的末尾而没有命中return语句,则函数也将返回。不返回任何内容与None使用Python 返回相同。

You could simply use

return

which does exactly the same as

return None

Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.


回答 1

我会建议:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

回答 2

您可以使用return不带任何参数的语句退出函数

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return
    do much much more...

或引发异常,如果您想被告知该问题

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        raise Exception("cause of the problem")
    do much much more...

you can use the return statement without any parameter to exit a function

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return
    do much much more...

or raise an exception if you want to be informed of the problem

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        raise Exception("cause of the problem")
    do much much more...