[英]What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?
Let's assume an iteration in which we call a function without a return value.让我们假设一个迭代,我们调用 function 没有返回值。 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
.如果我在 python 中实现此功能,那么 function 返回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"?有没有更好的方法来“退出没有返回值的 function,如果函数体中的检查失败”?
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.如果执行到达 function 主体的末尾而没有遇到return
语句,您的 function 也将返回None
。 Returning nothing is the same as returning None
in Python.什么都不返回与在 Python 中返回None
相同。
I would suggest:我会建议:
def foo(element):
do something
if not check: return
do more (because check was succesful)
do much much more...
you can use the return
statement without any parameter to exit a function您可以使用不带任何参数的return
语句退出 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...
return None
or return
can be used to exit out of a function or program, both does the same thing return None
或return
可用于退出 function 或程序,两者都做同样的事情quit()
function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter. quit()
function 可以使用,尽管不鼓励使用此 function 来制作实际应用程序,并且只能在解释器中使用。 import site
def func():
print("Hi")
quit()
print("Bye")
exit()
function can be used, similar to quit()
but the use is discouraged for making real world applications. exit()
function 可以使用,类似于quit()
但不鼓励在实际应用中使用。import site
def func():
print("Hi")
exit()
print("Bye")
sys.exit([arg])
function can be used and need to import sys
module for that, this function can be used for real world applications unlike the other two functions. sys.exit([arg])
function 可以使用,但需要为此import sys
模块,此 function 可用于实际应用,与其他两个功能不同。import sys
height = 150
if height < 165: # in cm
# exits the program
sys.exit("Height less than 165")
else:
print("You ride the rollercoaster.")
os._exit(n)
function can be used to exit from a process, and need to import os
module for that. os._exit(n)
function 可用于退出进程,需要import os
模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.