在函数结束之前(例如检查失败),在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)?

查看:135
本文介绍了在函数结束之前(例如检查失败),在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中退出函数(没有返回值)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆