Computer Science
Predict the output of the following code:
def express (x, n) :
if n == 0:
return 1
elif n % 2 == 0:
return express (x*x, n/2)
else:
return x * express (x, n-1)
express (2, 5)
Python Functions
4 Likes
Answer
The code will not print anything because it doesn't include a print statement. Instead, it returns a value without displaying it.
Explanation
The code defines a recursive function express(x, n) that takes two arguments x, n. Inside the function, it checks for three conditions: if n is 0, it returns 1; if n is even (checked using the modulo operator), it recursively calls itself with x*x and n/2; and if n is odd, it recursively calls itself with x and n-1, then multiplies the result by x. When express(2, 5) is called, it eventually evaluates to 32 but does not print or display anything.
Answered By
2 Likes
Related Questions
Predict the output of the following code.
def code(n): if n == 0: print(' Finally') else: print (n) code (10)Predict the output of the following code.
def code (n) : if n==0: print ( 'Finally' ) else: print (n) print (n-3) code (10)Consider the following Python function that uses recursion.
def check (n) : if n <=1: return True elif n % 2 == 0: return check (n/2) else: return check (n/1)What is the value returned by check(8) ?
Can you find an error or problem with the below code? Think about what happens if we evaluate check(3). What output would be produced by Python? Explain the reason(s) behind the output.
def check (n) : if n <=1: return True elif n % 2 == 0: return check (n/2) else: return check (n/1)