本文介绍了为什么函数以“返回0"结尾?而不是“返回"在python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您解释返回0"和返回"之间的区别?例如:

Could you please explain the difference between "return 0" and "return"?For example:

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

do_2():
    for i in xrange(5):
        do_sth()
    return

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

What is the difference between two functions above?

推荐答案

取决于用法:

>>> 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'

并且如Tichodroma提到的 0 不等于 None .但是,在布尔上下文中,它们都是 False :

And as mentioned by Tichodroma, 0 is not equal to None. However, in boolean context, they are both 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

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

More on Boolean context in Python: Truth Value Testing

这篇关于为什么函数以“返回0"结尾?而不是“返回"在python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:02