Python Forum

Full Version: recursion function (python beginner)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi all,

need help for the code below

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)
Output:
Recursion Example Results 1 3 6 10 15 21


how does python compute the above code?
how did k becomes greater than 0?
Huh Huh Huh

as per my understanding
if (k>0) then it should jump on else statement
(Aug-19-2019, 07:03 AM)everafter Wrote: [ -> ]as per my understanding
if (k>0)then it should jump on else statement
exactly the opposite - in this case it will execute lines 3-4

on line 10 you call your function and initial value of k is 6

you can visualise step-by-step execution here
(Aug-19-2019, 07:05 AM)buran Wrote: [ -> ]on line 10 you call your function and initial value of k is 6
oh that make sense to me, I thought tri_recursion(6) is the number times it will recur because I tried these steps, I changed 6 to 9 and the result is:
tri_recursion(6) #result has 6 lines
tri_recursion(9) #result has 9 lines
(Aug-19-2019, 07:13 AM)everafter Wrote: [ -> ]I thought tri_recursion(6) is the number times it will recur
actually that is also true (in this particular case, because you sum every number, i.e. on line 3 you change k by 1 when call tri_recursion(k-1)) - on line 4 you print intermediate results as well as the final one.

if you change your code
def tri_recursion(k):
  if(k>0): 
    result = k+tri_recursion(k-2) #NOTE THE DIFF HERE
    print(result)
  else:
    result = 0
  return result
 
print("\n\nRecursion Example Results")
tri_recursion(6)
Output:
Recursion Example Results 2 6 12 >>>