I'm working on the following recursive loop example from the Python Essentials 1, and I don't really understand what's happening, hoping someone can shed some light.
def fun(a):
if a > 30:
return 3
else:
return a + fun(a + 3)
print(fun(25))
The output is 56. I don't really understand what's happening with the function - it's almost like it's taking a + 3
making 28, and that value is then substituted into a
then returned, however I'm not sure if that's what's actually happening and I don't want to 'decide' that's the case if it's not.
Where it gets really interesting is when I started value substitution to try and make sense of it, substituting values in place of the 3
. I get the following:
return a + fun (a + 0) = // RecursionError: maximum recursion depth exceeded in comparison
return a + fun(a + 1) = 168
return a + fun(a + 2) = 84
return a + fun(a + 3) = 56
return a + fun(a + 4) = 57
return a + fun(a + 5) = 58
return a + fun(a + 6) = 28
return a + fun(a + 7) = 28
In fact any integer value greater than or equal to 6 seems to give the same answer, so I would assume I was wrong with my initial analysis of what's happening.
I also tried to put a while
loop in there to see what was happening as below:
def fun(a):
i = 1
if a > 30:
return 3
else:
while i <= 10:
return a + fun(a + i)
i += 1
print(i)
print(fun(25))
However this finishes the program with a value displayed of 168
, presumably as the value of a
is now over 30.
I think I may be making several massively erroneous assumptions here, hoping someone can help :)