为什么函数在 python 中以“return 0”而不是“return”结尾?

新手上路,请多包涵

你能解释一下“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 许可协议

阅读 635
2 个回答

取决于用途:

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

 >>> 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 中的布尔上下文: 真值测试

原文由 aneroid 发布,翻译遵循 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, NoneTypeint )。

原文由 Lukas Graf 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题