Search code examples
pythonfunctionrecursionreturn

Python - Recursive Function Without Return Logic


I had trouble understanding why this function returns None:

def rem(x, a):
    """
    x: a non-negative integer argument
    a: a positive integer argument

    returns: integer, the remainder when x is divided by a.
    """
    if x == a:
        return 0
    elif x < a:
        return x
    else:
        rem(x-a, a)

rem(7, 5)

I then realized that the last line in the function should be:

return rem(x-a, a)

I am still unsure as to what really happens in the first one. It looks like there are 2 seperate function calls, one returning 2 and the other None... any help?


Solution

  • All python function returns None if it doesn't terminate by a return statement. In your case, you successfully called the recursion but you discarded the result in the else part. And after the if-block, the default return None is implicitly executed.