Editor

Predict Recursive Output

Beginner · Predict the output · 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

Read this code and predict the output. Then write print() statements that produce the exact same output.

def mystery(n):
    if n <= 0:
        return
    mystery(n - 1)
    print(n)

mystery(3)

Notice that the print(n) is after the recursive call. Think carefully about the order.

# Print the exact output of the code above

More Recursion exercises

All Python exercises · 50 practice problems · Functions quiz