Why would a function end with "return 0" instead of "return" in python?
Depends on usage:
>>> 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'
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
More on Boolean context in 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
In python, a function would return None
either explicitly or implicitly.
e.g.
# 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
A python function would return 0
either because of some computation:
def add_2_numbers(a,b):
return a + b # 1 -1 would return 0
Or because of a magic
flag kind of thing, which is frowned upon.
But in python we don't use 0
to denote success because this:
if get_user(id):
would not evaluate to True
if we returned 0
therefore this if
branch would not run.
In [2]: bool(0)
Out[2]: False