Exercise
Recursive Function For Calculating Powe
Objective
Develop a Python program with a function that computes the result of raising one integer to the power of another integer (e.g., 5 raised to 3 = 5^3 = 5 × 5 × 5 = 125). This function should be implemented recursively.
For instance, you could use it like this: print(power(5, 3))
Example Python Exercise
Show Python Code
# Define the recursive function to calculate the power of a number
def power(base, exponent):
# Base case: if the exponent is 0, the result is 1
if exponent == 0:
return 1
# Recursive case: multiply base by the result of power(base, exponent-1)
else:
return base * power(base, exponent - 1)
# Main function to test the power function
def main():
# Test the power function with base 5 and exponent 3
print(power(5, 3)) # Expected output: 125
# Call the main function to execute the program
main()
Output
125
Share this Python Exercise