TalentJR

🐍 Python for kids · Class 7 · Lesson 13 of 18 · Free

Recursion – Functions That Call Themselves

⏱ About 35 minutes · ▶ run real Python here — nothing to install · no sign-in

In this lesson you will

  • Write a recursive function with a base case and a recursive case.
  • Trace how each call waits and then returns its answer.
  • Choose between recursion and a loop for a simple problem.

Stand between two mirrors and you see a mirror inside a mirror inside a mirror. A recursive function is like that: a function that calls itself. But unlike the mirrors, it must stop somewhere!

What is recursion in Python?

Recursion means a function calls itself. Each call solves a slightly smaller version of the same job.

Think of a rocket countdown. To count down from 3, say 3, then count down from 2.

Counting down from 2 is the same job, just smaller. So the function can hand it to itself.

🎬 How Python thinks — step 1 of 15Python is about to run line 1
▶def countdown(n):
2 if n == 0:
3 print("Lift off!")
4 return
5 print(n)
6 countdown(n - 1)
7
8countdown(3)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
3
2
1
Lift off!

💡 Watch n in the trace. Every new call gets its own n, one smaller than before.

What is a base case and why does recursion need one?

Every recursive function has two parts. The base case is the simple situation where the function stops.

The recursive case does a little work and calls the function again with a smaller value.

In countdown, n == 0 is the base case. Without it, the calls would never end.

Python allows about 1000 calls inside each other. After that it stops with a RecursionError.

🐍 Python — you can edit this code
Output
Climb one step, 3 left
Climb one step, 2 left
Climb one step, 1 left
Climb one step, 0 left
Reached the top floor!

💡 Ask two questions for every recursive function: When does it stop? Does every call move closer to that stop?

How does a recursive function return a value?

The factorial of 4, written 4!, is 4 × 3 × 2 × 1 = 24. It is used to count arrangements.

Notice that 4! is just 4 × 3!. And 3! is 3 × 2!. The same job keeps getting smaller.

Each call waits for the smaller call to return. Then it multiplies and returns its own answer.

So the answers travel back up the chain, like passing a tiffin back along a row of desks.

🎬 How Python thinks — step 1 of 12Python is about to run line 1
▶def factorial(n):
2 if n == 1:
3 return 1
4 return n * factorial(n - 1)
5
6answer = factorial(4)
7print("4! =", answer)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
4! = 24

💡 The calls go down 4, 3, 2, 1. The answers come back up 1, 2, 6, 24.

Can recursion work on lists and strings?

Yes. A list can be split into its first item and the rest of the list.

The sum of a list is the first item plus the sum of the rest. The rest is a smaller list.

The base case is an empty list, whose sum is 0. Slicing with [1:] gives the rest.

🎬 How Python thinks — step 1 of 11Python is about to run line 1
▶def total(marks):
2 if marks == []:
3 return 0
4 return marks[0] + total(marks[1:])
5
6print(total([40, 35, 25]))
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
100

How do I reverse a string with recursion?

A word can also be split: its first letter and the rest. Reverse the rest, then put the first letter at the end.

The base case is a word with 0 or 1 letters. Reversing it gives the same word.

This also lets us check palindromes, words that read the same both ways, like "malayalam".

🐍 Python — you can edit this code
Output
nohtyp
malayalam is a palindrome: True

Should I use recursion or a loop?

Most recursive functions can also be written with a loop. Both versions below add 1 + 2 + ... + n.

Loops are usually faster and never hit the 1000-call limit. Use them for simple counting jobs.

Recursion shines when a problem contains smaller copies of itself, like folders inside folders or family trees.

🐍 Python — you can edit this code
Output
55 55

💡 Same answer, two styles. Pick the one that is easier to read for that problem.

🤔 Predict the output

Think like Python: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

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

show(2)

Question 2. What does this print?

def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

print(power(2, 3))

Question 3. Here print comes after the recursive call. What does this print?

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

show(3)

🧩 Your challenge

Write a recursive function digit_sum(n) that adds the digits of a number. For 2026 it should give 2 + 0 + 2 + 6 = 10. Ask the user for a number and print the result.

Expected output (with the inputs given):
Enter a number: 2026
Sum of digits: 10
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

def countdown(n):
    print(n)
    countdown(n - 1)

countdown(3)

RecursionError: maximum recursion depth exceeded

✅ Right

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

countdown(3)

There is no base case, so the calls never stop. Python gives up after about 1000 calls inside each other.

❌ Wrong

def factorial(n):
    if n == 1:
        return 1
    n * factorial(n - 1)

print(factorial(3))

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

✅ Right

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(3))

Without return, the call gives back None. The next call then tries to multiply a number by None.

❌ Wrong

def countdown(n):
    if n == 0:
        print("Go!")
        return
    print(n)
    countdown(n - 2)

countdown(5)

RecursionError: maximum recursion depth exceeded

✅ Right

def countdown(n):
    if n <= 0:
        print("Go!")
        return
    print(n)
    countdown(n - 2)

countdown(5)

5, 3, 1, -1... jumps right over 0, so n == 0 is never true. Use n <= 0 to catch every case.

📌 Remember

  • Recursion means a function calls itself to solve a smaller copy of the same job.
  • The base case says when to stop; the recursive case moves one step closer to it.
  • Each call waits for the smaller call, then uses its returned answer.
  • Remember return in the recursive case, or the answer is lost as None.
  • Lists and strings can shrink with slicing, like marks[1:] or word[1:].
  • Loops are often simpler; recursion fits problems built from smaller copies of themselves.

Finished the quiz and the challenge?

Questions students ask

What is RecursionError in Python?

It means too many calls were waiting inside each other, usually because the base case is missing or never reached.

Is recursion faster than a loop?

Usually no. Each call takes extra memory and time. Recursion is chosen because some problems become much easier to write.

Can a recursive function have two base cases?

Yes. For example, a function can stop when a list is empty or when the item is found. Every path must reach one of them.

Where is recursion used in real programs?

It is used to search folders inside folders, explore family trees and game moves, and in fast sorting methods like merge sort.