Reputation: 30
I am hoping someone will explain it in a "like I am 5" fashion.
def WorryAboutMoney(money):
if (money > 3):
return print()
else:
print( money, end = " ")
WorryAboutMoney(money+1)
print( money, end = " ")
return
money = 1
WorryAboutMoney(money)
Output is:
1 2 3
3 2 1
Upvotes: 1
Views: 103
Reputation: 15515
What's going on can be illustrated by printing the depth of recursion:
def WorryAboutMoney(money, depth=0):
if (money > 3):
print(" " * depth + "[call {}]".format(depth))
return
else:
print("{}[call {}, before] {}".format(" " * depth, depth, money))
WorryAboutMoney(money+1, depth+1)
print("{}[call {}, after] {}".format(" " * depth, depth, money))
return
WorryAboutMoney(1)
Output:
[call 0, before] 1
[call 1, before] 2
[call 2, before] 3
[call 3]
[call 2, after] 3
[call 1, after] 2
[call 0, after] 1
Each call prints "before", then pauses while a recursive call is ongoing, then prints "after". The value of money
has not changed between the "before" and the "after" prints.
Upvotes: 0
Reputation: 2584
The return print()
is causing execution to return to the caller (which in this case is itself, the function WorryAboutMoney
- execution returns to the instruction right after the call in the caller, in this case - print( money, end = " ")
in the calling function.
Note that in you have 2 calls to print in each instance of WorryAboutMoney
: one before the recursive call (which prints the increasing numbers) and one after. Note that the call after the recursive call is only executed after the recursion fully unwraps. It gets executed for the first time (with money=3
) right after return print()
, then it returns and the same line is executed in the caller (money=2
) etc. - that is why you see the numbers decreasing.
Hope that clarifies it.
Upvotes: 1
Reputation: 805
I'll explain by steps, that will be easier to understand:
1 2 3
3 2 1
hope that it was "like you're 5" enough.
Upvotes: 2