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

2024-04-19 17:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

你能解释一下“return 0”和“return”的区别吗? 例如:

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

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

上面两个函数的区别是什么?


Tags: 函数inforreturndo区别xrangesth
3条回答

取决于用法:

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

作为mentioned by Tichodroma0不等于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中布尔上下文的更多信息:Truth Value Testing

def do_1():
    return 0

def do_2():
    return

# This is the difference
do_1 == 0 # => True
do_2 == 0 # => False

在python中,函数将显式或隐式返回None

例如

# Explicit
def get_user(id):
    user = None
    try:
        user = get_user_from_some_rdbms_byId(id)
    except:
        # Our RDBMS raised an exception because the ID was not found.
        pass
    return user  # If it is None, the caller knows the id was not found.

# Implicit
def add_user_to_list(user):
    user_list.append(user)   # We don't return something, so implicitly we return None

python函数将返回0,这可能是由于某些计算:

def add_2_numbers(a,b):
    return a + b      # 1 -1 would return 0

或者是因为一个magic标志类的东西,这是不受欢迎的。

但是在python中,我们不使用0来表示成功,因为:

if get_user(id):

如果返回0,则不会计算为True,因此此if分支不会运行。

In [2]: bool(0)
Out[2]: False

相关问题 更多 >