+ 1

# Can someone please help explain the step process in this coding.

def f(x): if x == 0: return 0 return x + f(x - 1) print(f(3)) The ‘f(x’ in line 4 is confusing me. Because I’m not to sure if that puts it through the function again all over again.

2 ответов

+ 4

It's recurrence
We are again calling the function but by decreasing the value of x by 1
Until and unless x doesn't becomes zero it will keep on adding the value of x and then return it .
So the fxn will return 3+2+1 =6 but as x becomes Zero it returns 0 and then it returns 6 .

+ 3

The function is a recursive function means return itself until the condition is not acceptable.
In your code, the beginning value is 3 and the condition is 0, the function decreases the value one by one and returns itself until the value becomes 0.
Running process:
Beginning value: 3
Return value: 3+f(2), 2 is greater than 0, so continue
Return value: 3+2+f(1), 1 is greater than 0, so continue
Return value: 3+2+1+f(0), 0 equals to 0, so the function stops to return itself.
I hope, it's clear enough.
Happy coding!