Skip to content
BENIBIX Learn

Recursion

Development🧩 Programming ConceptsFunctions

Also known as Recursive Function

A function that calls itself on a smaller job. A stop rule ends the chain.

Think of it like

Think of it like nesting dolls. Open one, find a smaller one, and go on to the tiny one.

Example

A countdown function prints 3, then calls itself with 2, then 1. At 0 the base case prints Go! and stops.

Why it matters

Some problems are built from smaller copies of themselves, like folders in folders. Recursion fits those.

Definition

Recursion is when a function calls itself. Each call works on a smaller part of the problem. A stopping rule, called the base case, ends the chain when the part is small enough. Then each call hands its answer back up to the one before. Without a base case, the calls never stop and the program crashes.

Example code

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

countdown(3)   # 3, 2, 1, Go!
Each call is one smaller, until n reaches 0 and the chain stops.

Common mistake

Forgetting the base case, or never getting closer to it. The calls pile up until the program crashes.

Key takeaways

  1. 1
    Calls itself. The function uses itself on a smaller part.
  2. 2
    Needs a base case. A stop rule ends the chain.
  3. 3
    Answers flow back. Each call hands its result up.

Learn it properly