Search code examples
pythonfunctionreturn

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


Could you please explain the difference between "return 0" and "return"? For example:

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

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

What is the difference between two functions above?


Solution

  • 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