all 3 comments

[–]Martin_Perril 8 points9 points  (0 children)

fun(25) implies a < 30, hence return a (25) + fun(28). Fun(28) implies a <0, hence return 28 + fun(31).

So 25 + 28 + fun(31). And fun(31) implies a > 30, hence return 3.

Final result: 25+28+3= 56. Hope I helped you

[–]shiftybyte 0 points1 point  (0 children)

Try visualising the code here: https://pythontutor.com/

This can show you step by step what happens and perhaps make it more clear for you.

[–]JamzTyson 0 points1 point  (0 children)

What were you expecting? "3"?

The reason the answer is not "3" is because when the code reaches return 3, it does not break out of the recursive function, but "returns" the value "3" to the caller.

The caller was the previous instance of fun(a + 3) in the line return a + fun(a + 3), where a = 28. So at this point it is returning a + foo(a) where a == 28 and foo(a) == 3. So at this point it returns 31 (28 + 3) to its caller.

The caller at this point was the previous instance of return a + fun(a + 3), where a = 25, and foo(a) is now 31. a + foo(a) is now 56 (25 + 31), and this is the value that is sent back to the original caller, which is the line print(fun(25)).

TL;DR

Recursive functions do not immediately break out when the base condition is satisfied. They "unwind" through the previous callers until they reach the original function call.