Andy
Andy

Reputation: 15

Why this recursion prints multiple lines?

Can someone please explain me how this Python recursion code works? I just cannot understand why it prints six numbers and not just one (21)... and why does it start with 1? Sorry I'm very noob, I know... Your kind help would be very much appreciated.

Code:

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

print("\n\nRecursion Results")
func(6)

Output:

Recursion Results
1
3
6
10
15
21

Upvotes: 0

Views: 129

Answers (2)

Princess E-Turtle
Princess E-Turtle

Reputation: 11

Well basically when your code runs the 3rd line (result = k + func(k - 1)), it first looks at fun(k-1) (which is 5 if you start with 6), so it runs that until you get to (result = k + func(k - 1)) again, in which it prioritizes fun(k-1) again... until your fun(k-1) == fun(0).

At fun(0) the code runs your else statement (so it printes nothing) and it will go back to the fun(1), in which it will print 1 before returning the value... until you get to fun(6).

If you want to see what your code does step by step, i would recommend you to use python tutor, which is a site that lets you see step by step what is happening in your code.

Have fun learning python!!!

(ps, here is the link for the site: https://pythontutor.com/visualize.html#mode=edit)

Upvotes: 1

CodeBoy
CodeBoy

Reputation: 3300

Well, every time func(k) gets called with k > 0, the print statement will be invoked. func is being called repeatedly or recursively so print is repeatedly called so you are seeing multiple lines.

Remove the print from your func and do print(func(6)) to display just the final result.

Upvotes: 3

Related Questions