swerWhat will be the output of the following Python code?def demo(p,q): if(p == 0): return q else: return demo(p-1,p+q)print(demo(4,5))
Question
What will be the output of the following Python code?
def demo(p,q):
if(p == 0):
return q
else:
return demo(p-1,p+q)
print(demo(4,5))
Solution
The given Python code defines a recursive function demo(p, q)
. This function checks if p
is equal to 0. If p
is 0, it returns q
. Otherwise, it calls itself with parameters p-1
and p+q
.
Let's break down the execution of demo(4,5)
:
demo(4,5)
is called. Sincep
is not 0, it callsdemo(3, 4+5)
which isdemo(3,9)
.demo(3,9)
is called. Sincep
is not 0, it callsdemo(2, 3+9)
which isdemo(2,12)
.demo(2,12)
is called. Sincep
is not 0, it callsdemo(1, 2+12)
which isdemo(1,14)
.demo(1,14)
is called. Sincep
is not 0, it callsdemo(0, 1+14)
which isdemo(0,15)
.demo(0,15)
is called. Sincep
is 0, it returnsq
which is 15.
So, the output of the Python code will be 15
.
Similar Questions
swerWhat will be the output of the following Python code?def demo(p,q): if(p == 0): return q else: return demo(p-1,p+q)print(demo(4,5))
correct answerWhat will be the output of the following Python code?def demo(x): if (x > 100): return x - 5 return demo(demo(x+11)); print(demo(45))
What will be the output of the following program in Python?print( 2 >3 and 4< 2)
What will be the output of the following Python code?def foo(k): k = [1]q = [0]foo(q)print(q)
What will be printed by the following code?for i in range(5): for j in range(5, 0, -1): if i == j: print(i, end=" ")1 2 3 44 3 2 1 004
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.