Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Recursion question

Name: Anonymous 2022-09-22 9:36

Sup /prog/. I'm at my wits end. I cannot figure out how this recursive function in python works for the life of me. Will anyone help me out?

def calc_sum(n):
if n==1:
return 1
else:
return n+calc_sum(n-1)

print(calc_sum(3)) # prints 6??

Name: Anonymous 2022-09-27 1:56

>>6
the function calls are nested, and the deepest one finishes first
calc_sum(3)=3+calc_sum(2)=3+2+calc_sum(1)=3+2+1=6
calc_sum(3) -> = calc_sum(2) -> calc_sum(1) = return 1
return 2+1
return 3+3

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List