🪆 Recursion

7th Grade 💻 Coding

Recursion is when a function calls itself, each time with a smaller version of the problem, until it reaches a simple case that stops it.

Free · US Letter · no sign-up
Google Classroom Save to Pinterest Email me

Example: a countdown. A function countdown takes a number n. If n is 0, it shows “Liftoff!” and stops. Otherwise, it shows n and calls itself with n - 1. So countdown(3) shows 3, 2, 1 and then “Liftoff!” The case that stops it is called the “base case.”

Without a base case, the function would keep calling itself forever — a lot like an infinite loop — and in Python the program would stop with an error. Recursion is an advanced idea, but a beautiful one: it fits problems made of parts that look like the whole, like the branches of a tree or folders inside folders.

For example

  • Nesting dolls: you open a doll and find a smaller one inside, until you reach the tiny doll that doesn’t open — the base case.
  • Two mirrors facing each other make a picture inside a picture inside a picture — visual recursion (but with no base case).

📌 Remember: Recursion = a function that calls itself + a base case that stops it.

Quick quiz

  1. What is recursion?

  2. What is a base case?

  3. Which object reminds you of recursion?

🔎 Ask Thinkapedia another question