-1

i need help understanding this recursion thing i am new to coding and trying to learn python

def tri_recursion(k):
    if(k > 0):
        result = k + tri_recursion(k - 1)
        print(result)
    else:
        result = 0
    return result

print("\n\nRecursion Example Results")
tri_recursion(6)
 
Recursion Example Results
1
3
6
10
15
21

i understood 1 and 3 i never understand why the answer is 6 by the third row because result = 3 + tri_recursion(3-1) print(result) which is 5 right ?

abinitio
  • 96
  • 5
  • `result = 3 + tri_recursion(3-1)` and `tri_recursion(3-1)` is `2 + tri_recursion(2-1)`. However, I think you have the `return` at the wrong place - it shouldn't be only for the `else` – VLAZ Sep 21 '22 at 15:44
  • Relevant: [Understanding how recursive functions work](https://stackoverflow.com/q/25676961) – VLAZ Sep 21 '22 at 15:44
  • you're missing a return statement – OrenIshShalom Sep 21 '22 at 15:46
  • Does this answer your question? [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement-how-is-it-different-from-printing) – OrenIshShalom Sep 21 '22 at 15:46
  • related: https://stackoverflow.com/a/73752048/3357352 – OrenIshShalom Sep 21 '22 at 15:49

2 Answers2

2

It may help to print out k with your result

def tri_recursion(k):
    if(k > 0):
        result = k + tri_recursion(k - 1)
        print(f"k: {k} = {result}")
    else:
        result = 0
    return result

print("\n\nRecursion Example Results")
tri_recursion(6)

produces

Recursion Example Results
k: 1 = 1
k: 2 = 3
k: 3 = 6
k: 4 = 10
k: 5 = 15
k: 6 = 21

So you can see for each k that it is itself + the result from the previous line.

saquintes
  • 1,074
  • 3
  • 11
0

Here's how it works:

tri_recursion(1): result = k = 1

tri_recursion(2): result = k + tri_recursion(2-1) = k + tri_recursion(1) = 2 + 1 = 3

tri_recursion(3): result = k + tri_recursion(3-1) = k + tri_recursion(2) = 3 + 3 = 6

... and so on

Hope it helps!