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))
Question
What 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))
Solution
The given Python code is a recursive function. Here's how it works:
- The function
demo(x)
is defined, which takes an integerx
as an argument. - Inside the function, there is an
if
condition that checks ifx
is greater than 100. Ifx
is greater than 100, it returnsx - 5
. - If
x
is not greater than 100, the function calls itself twice with the argumentx+11
. - The
print
statement at the end calls the function with the argument45
.
Now, let's trace the execution of the code:
demo(45)
is called. Since 45 is not greater than 100, it callsdemo(45+11)
ordemo(56)
.demo(56)
is called. Since 56 is not greater than 100, it callsdemo(56+11)
ordemo(67)
.demo(67)
is called. Since 67 is not greater than 100, it callsdemo(67+11)
ordemo(78)
.demo(78)
is called. Since 78 is not greater than 100, it callsdemo(78+11)
ordemo(89)
.demo(89)
is called. Since 89 is not greater than 100, it callsdemo(89+11)
ordemo(100)
.demo(100)
is called. Since 100 is not greater than 100, it callsdemo(100+11)
ordemo(111)
.- Now,
demo(111)
is called. Since 111 is greater than 100, it returns111 - 5
or106
.
So, the output of the Python code will be 106
.
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))
Select the correct answerWhat will be the output of the following Python code snippet if x=1?x<<2Options1248
What will be the output for following code snippet?x=5x=y-=1print(y)810Syntax errorNo error but no output
What will be the output after the following statements?x = 5 if x > 15: print('yes') elif x == 15: print('equal') else: print('no')Options15equalnoyes
What will be the output of the following statement?print(17 // 10)Options: Pick one correct answer from below1.712None of the Above
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.