Recursive Power Method
Design a function that uses recursion to raise a number to a power. The function should
accept two arguments: the number to be raised and the exponent. Assume that the exponent
is a nonnegative integer
Recursive Power Methdo using recursion program code:
def power(base, exponent):
"""
Recursive function to raise a number to a power.
Arguments:
- base: The number to be raised.
- exponent: The nonnegative integer exponent.
Returns:
- The result of raising base to the power of exponent.
"""
# Base case: If exponent is 0, return 1 (any number raised to 0 is 1).
if exponent == 0:
return 1
# Recursive case: Multiply base with the result of raising base to (exponent - 1).
# This effectively reduces the exponent by 1 with each recursive call.
return base * power(base, exponent - 1)
# Test the function
base = 2
exponent = 5
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
Executed Output:
def power(base, exponent):
"""
Recursive function to raise a number to a power.
Arguments:
- base: The number to be raised.
- exponent: The nonnegative integer exponent.
Returns:
- The result of raising base to the power of exponent.
"""
# Base case: If exponent is 0, return 1 (any number raised to 0 is 1).
if exponent == 0:
return 1
# Recursive case: Multiply base with the result of raising base to (exponent - 1).
# This effectively reduces the exponent by 1 with each recursive call.
return base * power(base, exponent - 1)
# Test the function
base = 2
exponent = 5
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
Executed Output:
2 raised to the power of 5 is: 32