Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Recursion Results
1
3
6
10
15
21

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading