Recursive Function

Hi. Would greatly appreciate any simple explanation on why the function below returns 56:

def fun(a):
    if a > 30:
        return 3
    else:
        return a + fun(a + 3)

print(fun(25))

Thank you so much.

There are many ways that people explore code to understand what it does.
These are two very common ways.

You can run the code in your mind and reason about it line by line.
Some people find it helpful to explain the code to another person.
That other person does not need to be a programmer.
The act of speaking out loud helps you understand code for lots of people, even experienced programmers.

The other common idea is to ask what you want to know as code runs and add print calls so that you can how code works. For example:

def fun(a):
    print(“start fun a=“, a)
    if a > 30:
        print(“return from if”)
        return 3
    else:
        print(“return from else”)
        return a + fun(a + 3)

print(fun(25))
2 Likes

You first: what do you think it should return instead, and why?

1 Like

Thanks for the code showing the steps. Honestly, I am still a little bit confused.
I thought answer would be 53… It is the " a + fun (a+3)" that confuses me.

If you run the version of the code I posted how many times is fun called and with what value of a?

fun was called 3x.
But for example, why is 2nd instance resulting to 28? When it is " a + fun (a+3)? Has an “a +” in front…

Well, what do you think the a part should have as a result? What do you think the fun(a + 3) part should have as a result? (Hint: what is a + 3? What does it mean if you write fun() and put something inside the parentheses?) What should you get if you add those two things together?

1 Like

Does this make it clearer:

def fun(a):
    if a > 30:
        return 3
    else:
        x = a + 3
        y = fun(x)
        z = a + y
        return z

If you got this function from a course or tutorial, then the writer may have a devious sense of humor.
It’s a pretty funky function, since its max is for fun(0) == fun(3) == 168, so it’s kind of difficult to get any intuition for how its behaving :slight_smile:

1 Like

Yes I get the flow of “a + fun (a+3)”, as in your representation above. Now I know where I got it wrong lol So silly of me that I just focused on "“a + fun (a+3)”, which made me frustrated because the function becomes never ending–fun (28)…fun (31)…fun(33)… But I didn’t really absorbed the condition that above 30, it just returns 3. LOL Thanks for taking the time out for the representation!

2 Likes

Yes, I get it now. Thank you!