# How to Write a Recursive Function to Find the Power of a Number in Python?

Estimated read time 1 min read

To write a recursive function to find the power of a number in Python, you can use the following approach:

``````def power(base, exponent):
if exponent == 0:
return 1
else:
return base * power(base, exponent-1)``````

In this example, we define a function called `power` that takes two parameters: `base` and `exponent`.

The function checks if the `exponent` is equal to zero. If it is, the function returns 1 since any number raised to the power of zero is 1.

If the `exponent` is not zero, the function recursively calls itself with the same `base` and `exponent-1` as arguments, and multiplies the result by the `base`. This continues until the `exponent` reaches zero.

Here’s an example of how to use the `power` function to calculate the value of 2 raised to the power of 3:

``````result = power(2, 3)
print(result) # Output: 8``````

In this example, we call the `power` function with `base=2` and `exponent=3`. The function calculates 2 raised to the power of 3 recursively as `2 * power(2, 2) * power(2, 1) * power(2, 0)`, which evaluates to 8. The resulting value is stored in the `result` variable and printed to the console.

Add yours