Python Program to Find Power of Number Using Recursion
def power(base, exp): return 1 if exp == 0 else base * power(base, exp - 1) which multiplies the base number by itself exp times recursively.Examples
How to Think About It
Algorithm
Code
def power(base, exp): if exp == 0: return 1 else: return base * power(base, exp - 1) print(power(2, 3)) # Output: 8
Dry Run
Let's trace power(2, 3) through the code
Initial call
power(2, 3) checks if exp == 0 (false), so returns 2 * power(2, 2)
Second call
power(2, 2) checks if exp == 0 (false), so returns 2 * power(2, 1)
Third call
power(2, 1) checks if exp == 0 (false), so returns 2 * power(2, 0)
Base case
power(2, 0) returns 1 because exp == 0
Return values
power(2, 1) returns 2 * 1 = 2 power(2, 2) returns 2 * 2 = 4 power(2, 3) returns 2 * 4 = 8
| Call | exp | Return value |
|---|---|---|
| power(2, 0) | 0 | 1 |
| power(2, 1) | 1 | 2 |
| power(2, 2) | 2 | 4 |
| power(2, 3) | 3 | 8 |
Why This Works
Step 1: Base case
When the exponent is zero, the function returns 1 because any number to the power of zero is 1.
Step 2: Recursive call
For exponents greater than zero, the function calls itself with the exponent decreased by one.
Step 3: Multiplication
Each recursive call multiplies the base number by the result of the smaller problem, building up the final power value.
Alternative Approaches
def power(base, exp): return pow(base, exp) print(power(2, 3)) # Output: 8
def power(base, exp, result=1): if exp == 0: return result else: return power(base, exp - 1, result * base) print(power(2, 3)) # Output: 8
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per decrement of the exponent, so it runs in linear time relative to the exponent.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to the exponent.
Which Approach is Fastest?
Using Python's built-in pow() is fastest and uses optimized C code, while recursion is educational but slower and uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive function | O(n) | O(n) | Learning recursion and small exponents |
| Built-in pow() | O(1) or optimized | O(1) | Fastest calculation for any exponent |
| Tail recursion | O(n) | O(n) | Conceptual efficiency but no Python optimization |