在 Python 中返回 True、False 和 None
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15604267/
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
Return True, False and None in Python
提问by duckduck
I have function acall function b(returns Trueor Falseto a), afterwards function acan return the result to be printed.
我有函数a调用函数b(返回True或False到a),之后函数a可以返回要打印的结果。
class C:
...
def a(self, data):
p = self.head
return self.b( p,data)
def b(self, p, data):
current = p
if current.data == data:
return True
else:
return False
if __name__=="__main__":
x = C()
print(x.a(1))
Sometimes it returns None eventhough it is intended to be True. I'm not sure what happened?
有时它会返回 None ,即使它是True. 我不确定发生了什么?
采纳答案by Ned Batchelder
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a returnstatement. When the code goes down that path, the function ends with no value returned, and so returns None.
如果没有看到您的实际代码,就不可能说出来。原因可能是通过不执行return语句的函数的代码路径。当代码沿着这条路径走时,函数结束时没有返回任何值,因此返回None.
Updated: It sounds like your code looks like this:
更新:听起来您的代码如下所示:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your Nonepath. You need to return the value that the recursive call returns:
那个 else 子句是你的None路径。您需要返回递归调用返回的值:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
顺便说一句:在这样的迭代程序中使用递归在 Python 中并不是一个好主意。改用迭代。此外,您没有明确的终止条件。

