0

Some say that return returns the value to the function. While learning DSA some referred, (in recursion) when "return" is used or when the base case hits, values are printed down the stack.

Example:

def print_sum(i, n, sum):
    if i==n:
        sum += n
        print(sum)
        return sum
    else:
        sum += i
        print_sum(i+1,n,sum)
    # print(i)

print(print_sum(1,5,0))

If return is returning the value to the function, why does print(print_sum(1,5,0)) show None as the output. This should provide "sum" i.e 15 as output as I have returned sum.

quamrana
  • 37,849
  • 12
  • 53
  • 71
ray_milan
  • 27
  • 7
  • 2
    [Function returns None without return statement](https://stackoverflow.com/q/7053652/15497888) you only `return` in one of the branches of your function. – Henry Ecker Sep 18 '21 at 20:17
  • 2
    "*if "return" is returning the value to the function, why does "print(print_sum(1,5,0))" provides None as output*" [Why does my recursive function return None?](https://stackoverflow.com/q/17778372) – VLAZ Sep 18 '21 at 20:17
  • 1
    `return` returns the value to the caller of the function. Your function only returns the value at the very bottom of the stack (when `i == n` and where the caller is another `print_sum` call). The top of the stack (where you call `print`) calls `print_sum` without returning the value, so it defaults to returning `None`, which is then printed. If you changed the `print_sum(i;+1, n, sum)` line to `return print_sum(i+1, n, sum)` then the return value would get propagated all the way up the stack. – Samwise Sep 18 '21 at 20:19
  • As @Samwise says: `return` returns the value to the caller of the function. In your case, the function is sometimes its own caller. That's what makes it recursive. In order to `return` the (intermediate values and) final value to the ultimate caller you need `return print_sum(i+1,n,sum)`. It is a failing of teachers to shortchange students by saying "`return` returns a value", without saying where that value goes. – quamrana Sep 18 '21 at 20:42
  • Thanks samwise. Your reply has better understanding than the vdo lectures. Thanks quamrana for your re-contribution. – ray_milan Sep 19 '21 at 03:53

0 Answers0