1

Below code returns "None" But, when I change (return sum) to (return print(sum)) it returns right value. Why does this problem occur?

def good(num,sum):
    if num == 0:
        return sum
    sum = sum + num
    num = num - 1
    good(num,sum)

sum = 0
a = 3
k = good(a,sum)
print(k)
  • 1
    Your recursive case has no return statement. Try `return good(num, sum)` in the last line of the function. – costaparas Dec 30 '20 at 13:37
  • "But, when I change (return sum) to (return print(sum)) it returns right value." **No, it does not**. You will notice that `k` does not get the correct value this way. `print` only causes things to be *displayed on the screen*; it has **nothing to do with** returning. – Karl Knechtel Aug 12 '22 at 23:19

1 Answers1

1

The return statement is missing!

Do this:

def good(num,sum):

    if num == 0:
        return sum
    sum = sum + num
    num = num - 1
    return good(num, sum)

This is because the function is called but is not returning the new values recursively.

One of the best website that explains this in depth and clearly is realpython.com, have a look especially at: maintaining-state but I suggest you to have a look at the whole article.

For sake of completeness I quote a section where I think is related to the issue you encountered:

Behind the scenes, each recursive call adds a stack frame (containing its execution context) to the call stack until we reach the base case. Then, the stack begins to unwind as each call returns its results.

  • unwind: Basically it returns it backward.

When dealing with recursive functions, keep in mind that each recursive call has its own execution context.

Other Stack Overflow Related questions

Federico Baù
  • 6,013
  • 5
  • 30
  • 38