1

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?

PYB
  • 503
  • 6
  • 20
  • 1
    It's unclear what you mean by this `It looks like there are 2 seperate function calls, one returning 2 and the other None... any help?` – liamhawkins Feb 21 '19 at 17:12
  • the first function is simply incorrect, there must be `return` in the last line anyway – sanyassh Feb 21 '19 at 17:13

1 Answers1

2

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.

adrtam
  • 6,991
  • 2
  • 12
  • 27