为什么函数在Python中以“返回0”而不是“返回”结尾?

alw*_*btc 4 python return function

您能否解释一下“返回0”和“返回”之间的区别?例如:

do_1():
    for i in xrange(5):
        do_sth()
    return 0

do_2():
    for i in xrange(5):
        do_sth()
    return 
Run Code Online (Sandbox Code Playgroud)

上面两个功能有什么区别?

ane*_*oid 6

取决于用法:

>>> def ret_Nothing():
...     return
... 
>>> def ret_None():
...     return None
... 
>>> def ret_0():
...     return 0
... 
>>> ret_Nothing() == None
True
>>> ret_Nothing() is None  # correct way to compare values with None
True
>>> ret_None() is None
True
>>> ret_0() is None
False
>>> ret_0() == 0
True
>>> # and...
>>> repr(ret_Nothing())
'None'
Run Code Online (Sandbox Code Playgroud)

并且如Tichodroma所述0不等于None。但是,在布尔上下文中,它们都是False

>>> if ret_0():
...     print 'this will not be printed'
... else:
...     print '0 is boolean False'
... 
0 is boolean False
>>> if ret_None():
...     print 'this will not be printed'
... else:
...     print 'None is also boolean False'
... 
None is also boolean False
Run Code Online (Sandbox Code Playgroud)

有关Python中布尔上下文的更多信息:真值测试


Luk*_*raf 5

在 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
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,foobar返回qux完全相同的内置常量None

  • fooNone由于return缺少语句而返回,并且None如果函数未显式返回值,则它是默认返回值。

  • bar返回,None因为它使用return不带参数的语句,该语句也默认为None.

  • qux返回,None因为它明确地这样做了。

zero然而完全不同并返回整数0

如果评估为布尔值0None都评估为False,但除此之外,它们非常不同(事实上,NoneType和是不同的类型int)。