Why would a function end with return 0 instead of return in python?

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

In Python, every function returns a return value, either implicitly or explicitly.

>>> 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 doesnt explicitly return a value.

  • bar returns None because it uses a return statement without an argument, which also defaults to None.

  • qux returns None because it explicitly does so.

zero however is entirely different and returns the integer 0.

If evaluated as booleans, 0 and None both evaluate to False, but besides that, they are very different (different types in fact, NoneType and int).

Why would a function end with return 0 instead of return in python?

def do_1():
    return 0

def do_2():
    return

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

Leave a Reply

Your email address will not be published. Required fields are marked *