0

So I'm working on a helper function to help with a recursion problem I recently received from class, and this is what it looks like:

def helper(a, b):
    if (a % b == 0 and b > 1):
        return False
    elif (a%b != 0 and b > 1):
        helper(a, b - 1)

If I put in something like (12, 11), I expect the result to be False, but I instead get met with None! Why does it do that? If I replace "return False" with a print statement, it comes out fine, so it seems like the return statement is being completely ignored. How should I fix this? Thanks!

03kkim
  • 41
  • 3

1 Answers1

4

You must return the result of the last line:

def helper(a, b):
    if a % b == 0 and b > 1:
        return False
    elif a % b != 0 and b > 1:
        return helper(a, b - 1)  # <--- Return a value here.

Also, if b <= 1, Python won't execute neither the if nor the elif branches. In this case, the function will return None.


Why I must use return before the call to helper?

Let's examine the case in which a = 8, b = 5. a % b != 0 and b > 0 is True, and the function will call helper(8, 4).

helper(8, 4) is a new function call, which has nothing to do with helper(8, 5). It will check if a % b == 0 and b > 1 (which is True), and will return False to the place where helper(8, 4) was called from.

If there is no return statement before helper(8, 4), your first function call (helper(8, 5)) will execute helper(8, 4) but won't do anything with the value returned from it.

You must use return to tell the caller what is the result of the execution.

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64