+ 1
Is the value get changed when we envoke function in itself?
I got the output 56. But a is 25 and fun(a + 3) is 28. so 25 + 28 should be 53. Why it is 56 not 53 https://code.sololearn.com/cpSQ25NCO3IX/?ref=app Another code has the same issue! why it is 11 not 10 https://code.sololearn.com/cnJ36eQf666O/?ref=app
6 Respostas
+ 3
(1)
a(25) + a(28) + a(31)
= 25 + 28 + 3 #a(31) -> (31 > 30). returns 3
= 56
(2)
fib(6) + fib(4) + fib(2)
= 6 + 4 + 1 #fib(2) -> (2 < 3). returns 1
= 11
+ 2
Ok see the output is 56 because when a is less than 30 i.e. 25 gets printed and fun(a+3) is called which is 28 so here again 28 is less than 30 again the fun(a+3) is called now value of a becomes 31 .... Value returned is 3 so as you are returning a+fun(a+3) and the function returns 3 therefore, 28+3 is returned which is 31 now the program calculates sum of 25+31 which is 56.
+ 2
The function is called recursively and each time the function is called it returns value to the previous function it is called into.
See, when a=25, fun(25+3) is called which is fun(28) here 28<30 so again fun(28+3) is called which is fun(31).
Now, here 31>30 therefore the code returns 3 to the previous function that is fun(28).
Now the function fun(28) returns 28 + the value returned by fun(28+3) which is 3 so it returns 31 to the previous function which is fun(25).
In fun(25) the value returned is 25+ value returned by fun(25+3) that is 31. Therefore total 25+31=56.
And similarly for the second code.
I think you need to brush up your recursion concepts.
+ 2
The current function stops and returns the value in the function where it is called. The whole program doesn't stop.
+ 1
i dont understand what you are trying to explain. Do you want to say that this function will run multiple times?
i learn that when we use return statement. The function execution get stop. then why it is running again and again.
+ 1
try changing to see the result:
#recursion Function
def fun (a):
if a> 30:
a = 3
print (a)
else:
print (a)
a += fun (a + 3)
return a
print (fun (25))
so fun () is called three times, and outputs =>
25
28
3
56
i.e. sums everything (a)