你能解释一下“return 0”和“return”的区别吗?例如:
do_1():
for i in xrange(5):
do_sth()
return 0
do_2():
for i in xrange(5):
do_sth()
return
上面两个函数有什么区别?
原文由 alwbtc 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Python 中, 每个 函数都会隐式或显式地返回一个返回值。
>>> def foo():
... x = 42
...
>>> def bar():
... return
...
>>> def qux():
... return None
...
>>> def zero():
... return 0
...
>>> print foo()
None
>>> print bar()
None
>>> print qux()
None
>>> print zero()
0
As you can see, foo
, bar
and qux
return exactly the same, the built in constant None
.
foo
returns None
because a return
statement is missing and None
is the default return value if a function doesn’t explicitly return a value .
bar
returns None
because it uses a return
statement without an argument, which also defaults to None
.
qux
返回 None
因为它明确地这样做了。
zero
然而完全不同并返回 整数 0
。
If evaluated as booleans , 0
and None
both evaluate to False
, but besides that, they are very different (different types in fact, NoneType
和 int
)。
原文由 Lukas Graf 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答865 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
取决于用途:
正如 Tichodroma 所提到的,
0
不等于None
。但是,在 布尔上下文中,它们都是False
:更多关于 Python 中的布尔上下文: 真值测试