Computer Science
What is the output of the following snippet?
def fun(n):
if (n > 100):
return n - 5
return fun (fun (n+11) )
print(fun(45))
- 50
- 100
- 74
- Infinite loop
Python Functions
1 Like
Answer
100
Reason — Initially, the function fun
is called with the argument 45. Since 45 is less than 100, the else block is executed, and fun
is called recursively with the argument fun(n+11)
. This leads to another recursive call fun(56)
, as 45 + 11 = 56. Again, since 56 is less than 100, the else block is executed, and another recursive call fun(n+11)
is made with n = 67. This process continues until n exceeds 100, at which point the base case is triggered.
Answered By
3 Likes
Related Questions
Fill in the line of code for calculating the factorial of a number:
def fact(num): if num == 0: return 1 else: return...............
- num*fact (num-1)
- (num-1) * (num-2)
- num* (num-1)
- fact (num) *fact (num-1)
Which of the following statements is false about recursion?
- Every recursive function must have a base case.
- Infinite recursion can occur if the base case isn't properly mentioned.
- A recursive function makes the code easier to understand.
- Every recursive function must have a return value.
What happens if the base condition isn't defined in recursive programs?
- Program gets into an infinite loop
- Program runs once
- Program runs n number of times, where n is the argument given to the function
- An exception is thrown
Assertion (A): Function can take input values as parameters, execute them and return output (if required) to the calling function with a return statement.
Reasoning (R): A function in Python can return multiple values.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.