Search code examples
pythonrecursion

Python Recursion Incrementing


I am teaching my self python by working through a few books. I have been able to work through the examples and get the foundational understanding. However, python recursion is stumping me.

I have included the code below. and in a screen shot. It seems to me that the first output would be 6 + 5 = 11, not 1 as is what the code prints as result. What is missing is the incrementor for k. I am assuming that the has an auto increment that starts at 0 and working up to 6

The question is, How is this code incrementing? I appreciate any guidance.

The printed results are:

1
3
6
10
15
21
def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result)
  else:
    result = 0
  return result

tri_recursion(6)

Solution

  • Agree with Barmar

    The key is this line result = k + tri_recursion(k - 1)

    Think of the recursive call as moving to the first line of the function again with k-1 as the input. Check out this visual explanation at around four minutes https://youtu.be/nuML9SmdbJ4.