Python coding practice

Implement power(base, exp)

Write a recursive Python function that computes base raised to the power exp. Your code runs directly in the browser — no Python installation required.

The problem

Exponentiation can be expressed recursively: any number raised to the power exp equals that number multiplied by itself raised to exp - 1. When exp reaches zero the result is always 1 — that is the base case.

power(2, 0) = 1
power(3, 1) = 3 × power(3, 0) = 3 × 1 = 3
power(2, 3) = 2 × 2 × 2 × 1 = 8
power(5, 3) = 5 × 5 × 5 × 1 = 125

Your function must pass these tests:

  • power(2, 0)1
  • power(3, 1)3
  • power(2, 8)256
  • power(5, 3)125
  • power(10, 4)10000

Write your solution below, then click Run Tests:

Advertisement

Hints

Hint 1 — The recursive relationship

base^exp = base × base^(exp-1). Each recursive call reduces exp by one, so the base case exp == 0 is guaranteed to be reached.

Hint 2 — Tracing power(2, 3)
power(2, 3) = 2 × power(2, 2)
power(2, 2) = 2 × power(2, 1)
power(2, 1) = 2 × power(2, 0)
power(2, 0) = 1   ← base case

Unwinding:
power(2, 1) = 2 × 1 = 2
power(2, 2) = 2 × 2 = 4
power(2, 3) = 2 × 4 = 8
Hint 3 — Full solution
def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

More coding problems