New course! Every coder should learn Generative AI!
Try a free lesson0
Can anyone explain this code please
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)
4 Answers
+ 4
Sure! This is an example of a recursive function in Python that calculates the sum of the numbers from `k` to `1`. Here's how the code works:
1. The function `tri_recursion` takes one parameter `k`.
2. The function checks whether `k` is greater than 0. If it is, the function calculates the sum of `k` and the result of calling `tri_recursion` with the argument `k 1`. This is done recursively until `k` becomes 0.
3. If `k` is not greater than 0, the function sets the `result` to 0.
4. The function returns the `result`.
5. Finally, the function is called with the argument `6`, and the result is printed to the console.
So when you run this code, it should output:
Recursion Example Results
1
3
6
10
15
21
The output shows the sum of the numbers from 6 to 1, printed in descending order. The first call to tri_recursion calculates the sum of 6+5+4+3+2+1, which is 21.
0
Really I didn't get this one it's confusing more
0
Please tag "Python" instead of "aghsj".
0
Well there is a good explain about this but well maybe this help you
You call the function with 6 so the function take this 6 and add every number between 6 and 0 to this until you reached that 0. If you call the function with 10 it will do :
10+9+8+7+6+5+4+3+2+1