I don’t know python, but…
First of all, this does nothing unless you pass it something. I changed the last line to:
Recursion is tricky business. It makes no sense … until you get it. And even then it takes a while to fully sink it.
Whenever I am confused, I start logging out data to see what happens. So, I add a log statement to your code:
print("calling tri_recursion with", k)
result = k+tri_recursion(k-1)
print("result = ", result)
result = 0
print("\n\nRecursion Example Results")
Now I can see what is happening.
Recursion Example Results
calling tri_recursion with 4
calling tri_recursion with 3
calling tri_recursion with 2
calling tri_recursion with 1
calling tri_recursion with 0
result = 1
result = 3
result = 6
result = 10
result =... line, it never fully evaluates before another all is made. In other words, it never makes it to the next line before calling the function again. It keeps calling that function, keeping track of those calls and values in the call stack, until we finally call it with
0. Then we return that value back. As that value gets sent back to the previous call, that
result =... line can finish and then the next line gets evaluated. This happens over and over as the call stack “unwinds” and renders its values.
Recursion is a difficult topic and not one that can be explained here. Just stick with it. There might be a good youtube video that will help you explain. Like I said, it’s kind of a weird concept until it “clicks”. Don’t get frustrated.