Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
alwbtc Avatar asked Sep 10 '12 09:09

alwbtc


2 Answers

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

like image 79
aneroid Avatar answered Nov 15 '22 22:11

aneroid


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 doesn't 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).

like image 27
Lukas Graf Avatar answered Nov 15 '22 22:11

Lukas Graf