+ 1

Python

Can some one help me with this function ...? def f (n): If n==0: return 0 else: return f (n-1)+100 print(f (3)) O/p:- 300 How it was compiled..?

22nd May 2021, 7:59 AM
Cran
Cran - avatar
2 Answers
+ 2
that's a recursive function (a function calling itself) f(3) => n = 3 n != 0, so return f(2)+100 f(2) => return f(1)+100 f(1) => return f(0)+100 f(0) => return 0... finally, reading backward, f(3) return: 0 + 100 + 100 + 100 300
22nd May 2021, 8:10 AM
visph
visph - avatar
+ 2
In this program "n" Value is 3 that is : f(n)=f(3) , hence n=3,You called the function in line 6.Then it goes to def function and execute the condition in the function. First it goes to if condition, we know n value is 3 , but the if condition is n==0 , 3 is not equal to zero, so it will execute else statement. In else statement we have f(n-1) +100 that is : f(3-1) +100 f(2) +100 #now n value becomes 2, it will iterate for value 2 from the start. here n value not equal to 2 , it executes else statement, now It will return f(2-1) +100+100 return f(1) +100+100 #now n=1, Again it will start to iterate from the beginning for the n value 1.Again 1 is not equal to 0, so that again it will execute else statement that is : return f(1-1) +100+100+100 return f(0) +300 Now it will execute for the n value 0 It will iterate from the beginning again and it satisfy the if condition that is n==0 Now it will return f(0) +300,f(0) is 0 , so return 0+300, hence finally the output is 300
22nd May 2021, 8:34 AM
Nethravathi M N
Nethravathi M N - avatar