>>> 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
# 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
取决于用法:
作为mentioned by Tichodroma,
0
不等于None
。然而,在布尔上下文中,它们都是False
:关于Python中布尔上下文的更多信息:Truth Value Testing
在python中,函数将显式或隐式返回
None
。例如
python函数将返回
0
,这可能是由于某些计算:或者是因为一个
magic
标志类的东西,这是不受欢迎的。但是在python中,我们不使用
0
来表示成功,因为:如果返回
0
,则不会计算为True
,因此此if
分支不会运行。相关问题 更多 >
编程相关推荐