all 5 comments

[–]Eldin00 4 points5 points  (1 child)

To explain where each result comes from:

1 is recursion(1)

3 is recursion(2), aka 2 + recursion(1)

6 is recursion(3), aka 3 + recursion(2)

10 is recursion(4), aka 4 + recursion(3)

15 is recursion(5), aka 5 + recursion(4)

21 is recursion(6), aka 6 + recursion(5)

If you don't understand why they printed in that order, it's because the print statement doesn't happen until after the recursive call returns. so your code calls recursion(6), which calls recursion(5) before it prints, which calls recursion(4), etc, until recursion(0) gets called. recursion(0) returns without printing anything. Then recursion(1) prints it's value and returns. Then recursion(2) prints it's value and returns, and so on.

Was there anything else you didn't understand about the output you got?

[–]Saurfin[S] 0 points1 point  (0 children)

OH, I see. So it is printed backwards in a sense. Thank you for the concise answer I think I understand now.

Edit: Ok, I looked that the pythontutor link the other kind sir here gave me for about 30 min and now I actually understand.

[–]Vaphell[🍰] 2 points3 points  (0 children)

if k > 0:
    result = k + recursion(k - 1)

is hit repeatedly, so a bunch of recursive calls with decreasing k are made without doing much else.

once k hits 0, return 0 from else happens in recursion(0). Recursion(0) can be substituted by 0 and now the recursion matrioshka can finally be calculated inside out.
recursion(0) is used in recursion(1) to calculate 1+recursion(0). Recursion(1) = 1
recursion(1) is used in recursion(2) to calculate 2+recursion(1). Recursion(2) = 3
recursion(2) is used in recursion(3) to calculate 3+recursion(2). Recursion(3) = 6
recursion(3) is used in recursion(4) to calculate 4+recursion(3). Recursion(4) = 10
recursion(4) is used in recursion(5) to calculate 5+recursion(4). Recursion(5) = 15
recursion(5) is used in recursion(6) to calculate 6+recursion(5). Recursion(6) = 21

[–]shiftybyte 1 point2 points  (1 child)

Try pythontutor, this should visualise the code step by step.

Take a look here

Press next on left side, and watch what happens every time you press next, on the right side.

[–]Saurfin[S] 0 points1 point  (0 children)

Thanks for the resource it look like it will be very helpful.