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
>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.