Editor

Fix the Broken Power Function

Intermediate · Fix the bug · from Python Recursion: How It Works, When to Use It, and Examples

From the lesson: Python Recursion: How It Works, When to Use It, and Examples

Imagine a set of Russian nesting dolls. You open the biggest one and find a smaller one inside. Open that, and there's an even smaller one. You keep opening until you reach the tiniest doll that doesn't open - that's the end.

Read the lesson

This recursive function should calculate base raised to the power of exp (like base ** exp). But it has two bugs.

Fix both bugs so the output is:

8
1
81
def power(base, exp):
if exp == 0:
return 0
return base + power(base, exp - 1)
print(power(2, 3))
print(power(5, 0))
print(power(3, 4))

More Recursion exercises

All Python exercises · 50 practice problems · Functions quiz