Junior Codes
The Sky Expedition · stretch

Recursion in Python for Kids

Solve a problem by having a function call a smaller version of itself.

Start Wonderwild free with Pip

Try 5 starter activities free. Full access is ₹499 a year.

This mission is part of full access. The first missions are free to try.

Recursion, explained simply

Recursion is when a function calls itself. It sounds like a loop that never ends, but done well, each call works on a slightly smaller problem.

Every recursive function needs a base case: a simple situation where it stops calling itself and just gives an answer. Without one, Python eventually stops with a RecursionError.

Think of walking down a staircase: to get down 5 steps, take one step, then get down 4 steps. When there are 0 steps left, you are done.

Example: Walk down the stairs

def walk_down(steps):
    if steps == 0:
        print("At the bottom!")
        return
    print("Step", steps)
    walk_down(steps - 1)

walk_down(3)

Output

Step 3
Step 2
Step 1
At the bottom!

Try this

  • Write a recursive function that adds up all the numbers from 1 to n.
  • Move the print line after the recursive call and predict the new order.
  • Remove the base case and read the error Python gives.

Practise it in Wonderwild

“The staircase inside a staircase”

Mission 35 in The Sky Expedition, one of 36 Python missions in Wonderwild.

Your child writes and runs real Python in the browser while Pip reacts to every line. Nothing to install. For ages 7+.

Start Wonderwild free with Pip

Try 5 starter activities free. Full access is ₹499 a year.

This mission is part of full access. The first missions are free to try.

Questions parents and kids ask

Is recursion better than a loop?+

Not always. Many problems are simpler with a loop. Recursion shines with things that contain smaller copies of themselves, like folders inside folders or branching trees.

What is a base case?+

The condition that stops the recursion. It is the smallest version of the problem, which the function can answer directly.

Prefer learning with a teacher?

Our live Python for Young Developers course teaches these ideas in small online classes led by a software engineer, with projects and feedback. Every live course also includes 12 months of full Wonderwild access for practice.

See the Python for Young Developers course