Search code examples
pythonrecursionreturn

In a recursive Python function, why does it matter what parameters are returned?


I thought I understood recursive functions but realised I don't actually understand what is happening under the bonnet

Running this Python code to generate a triangular series gives the expected values

def fib(k):
    result = 0
    if(k > 0):
        result = k + fib(k - 1)
        print(f'after call k is {k} and result is {result}')
    else:
        print()
    return result
    #return k

print("Recursion Example Results")
fib(6)

And this is what it returns:

Recursion Example Results

after call k is 1 and result is 1
after call k is 2 and result is 3
after call k is 3 and result is 6
after call k is 4 and result is 10
after call k is 5 and result is 15
after call k is 6 and result is 21

So this is printing intermediate values, but I don't understand why that depends on what is finally returned

So if I change the code to return k:

def fib(k):
    result = 0
    if(k > 0):
        result = k + fib(k - 1)
        print(f'after call k is {k} and result is {result}')
    else:
        print()
    #return result
    return k

print("Recursion Example Results")
fib(6)

I get this:

Recursion Example Results

after call k is 1 and result is 1
after call k is 2 and result is 3
after call k is 3 and result is 5 
after call k is 4 and result is 7 
after call k is 5 and result is 9 
after call k is 6 and result is 11 

Why the difference and how is it calculating this? Why is it not returning k = 1,2,3,4,5,6?


Solution

  • When you are returning k then result becomes result = k + k - 1 and when you are returning result it performs Additition of all the number in decreasing order, like for 6 it will be 6+5+4+3+2+1