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

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)?(在函数结束(例如检查失败)之前在 python 中退出函数(没有返回值)的最佳方法是什么?)

本文介绍了在函数结束(例如检查失败)之前在 python 中退出函数(没有返回值)的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设一个迭代,我们调用一个没有返回值的函数.这个伪代码解释了我认为我的程序应该表现的方式:

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...

如果我在 python 中实现它,我会感到困扰的是,该函数返回一个 None.有没有更好的方法来退出一个没有返回值的函数,如果函数体中的检查失败"?

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"?

推荐答案

你可以简单地使用

return

和

return None

如果执行到达函数体的末尾而没有遇到 return 语句,您的函数也将返回 None.在 Python 中不返回任何内容与返回 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.

这篇关于在函数结束(例如检查失败)之前在 python 中退出函数(没有返回值)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐