在python中,如果一个函数没有return语句,它返回什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15355083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:53:39  来源:igfitidea点击:

In python, if a function doesn't have a return statement, what does it return?

pythonpython-3.x

提问by zds_cn

Given this example function:

鉴于此示例函数:

def writeFile(listLine,fileName):
    '''put a list of str-line into a file named fileName'''
    with open(fileName,'a',encoding = 'utf-8') as f:
        for line in listLine:
            f.writelines(line+'\r\n')
    return True

Does this return Truestatement do anything useful?

return True句话有什么用吗?

What's the difference between with it and without it? What would happen if there were no return function?

有它和没有它有什么区别?如果没有返回函数会发生什么?

采纳答案by Travis Bear

If a function doesn't specify a return value, it returns None.

如果函数未指定返回值,则返回None.

In an if/then conditional statement, Noneevaluates to False. So in theory you could check the return value of this function for success/failure. I say "in theory" because for the code in this question, the function does not catch or handle exceptions and may require additional hardening.

在 if/then 条件语句中,None计算结果为 False。所以理论上你可以检查这个函数的返回值是否成功/失败。我说“理论上”是因为对于这个问题中的代码,该函数不会捕获或处理异常,并且可能需要额外的强化。

回答by GodMan

The function always returns Noneif explicit returnis not written.

None如果return未写入显式,则该函数始终返回。

回答by Will Richardson

If you have the return Trueat the end of the function, you can say stuff like: a=writeFile(blah, blah)

如果你return True在函数的末尾有 ,你可以这样说:a=writeFile(blah, blah)

However, because it will always be True, it is completely pointless. It would be better to return True if the file was written correctly, etc.

然而,因为它永远是True,所以它完全没有意义。如果文件写入正确,则返回 True 会更好,等等。

If you don't explicitly return anything, the value will be None

如果您没有明确返回任何内容,则该值将是 None

回答by dora

It does not make much sense to have a return statement on its own without being attributed or checked for a functionality.

如果没有归属或检查功能,单独使用 return 语句没有多大意义。

Python returns None if nothing is returned. In your case you should probably return true if the opening file and writting is successful

如果没有返回任何内容,Python 将返回 None。在您的情况下,如果打开文件和写入成功,您可能应该返回 true