Python Forum

Full Version: How returns behave in a function with multiple returns?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The code below returns 8. Why does not it return 2 instead? I do not understand how return behaves in the code below. what is the rule? Thanks for your help.. khasbay
def f(x):
    if x==0:
        return 2
    else:
        return x+f(x-1)

print(f(3))
Follow the function calls to compute the value for f(3).

You call your function f(3).

In the function, 3 != 0, so the function returns 3 + f(2).

We call f(2). 2 != 0, so the function returns 2 + f(1).

We call f(1). 1 != 0, so the function returns 1 + f(0).

We call f(0). 0 == 0, so the function returns 2

We have these values for f()
f(0) = 2
f(1) = 1 + f(0) = 3
f(2) = 2 + f(1) = 5
f(3) = 3 + f(2) = 8

Recursion is when a function calls itself. the value of f(3) is slightly confusing not because it has two return statements, but because it uses recursion. This is the same function with one return statement.
def f(x):
    return 2 if x == 0 else x + f(x-1)

print(f(3))