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.

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

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!