In our programming journey, we have used loops like for and while to repeat a block of code multiple times. However, there is another powerful and elegant way to solve repetitive problems in computer science. Instead of relying on a loop to do the work, you can design a function that solves a problem by breaking it down into smaller versions of itself.
On an advanced level, when analyzing algorithms or structuring data on platforms like AI Learner Tech, you will frequently encounter this concept.
In programming, when a function calls itself directly or indirectly to solve a problem, it is called Recursion.
The Concept of Recursion #
To understand recursion, think about a real-world analogy like looking into two parallel mirrors. The reflection in the first mirror is reflected in the second mirror, which is reflected back into the first, creating an endless series of images.
In code, a recursive function keeps calling itself to process a smaller chunk of the problem.
However, just like a while loop needs a stopping condition to prevent it from running forever, a recursive function must have a clear instruction that tells it when to stop calling itself. Without this stopping point, your function will create an infinite loop and crash the program.

The Two Vital Components of a Recursive Function #
Every recursive function you write must contain two specific parts: the Base Case and the Recursive Case.
- The Base Case: This is the condition that stops the function from calling itself any further. It handles the simplest possible input that can be solved directly.
- The Recursive Case: This is the part of the function where it reduces the problem into a slightly smaller version and calls itself again.
def countdown(number):
# 1. Base Case (The stopping condition)
if number <= 0:
print("Blast off!")
# 2. Recursive Case (The self-calling step)
else:
print(number)
countdown(number - 1)
In the example above, if you call countdown(3), Python checks the base case. Since 3 is not less than or equal to 0, it moves to the recursive case.
It prints 3 and then calls countdown(2). This process repeats until the number reaches 0, hitting the base case and stopping the program safely.
Behind the Scenes: The Call Stack #
Whenever you call a function in Python, your computer sets aside a chunk of its temporary memory to keep track of that function’s variables. This memory area is called the Call Stack.
With recursion, each time a function calls itself, Python pauses the current execution and places a brand-new layer on top of the stack.

If your function calls itself too many times without hitting a base case, the stack runs out of memory. This causes a specific error in Python known as a RecursionError (maximum recursion depth exceeded). By default, Python limits the number of recursive calls to around 1000 to prevent your system from running out of RAM.
Let’s Write Code: Basic to Advanced #
Let’s explore practical examples that progress from simple counting to classic mathematical calculations.
Example: Calculating a Factorial (Intermediate) #
In mathematics, the factorial of a number n (written as n!) is the product of all positive integers less than or equal to n.
For example, 4!=4×3×2×1=24. We can write this recursively because 4!=4×3!.
def calculate_factorial(n):
# Base case: 1! is always 1
if n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * calculate_factorial(n - 1)
# Running the factorial calculator
result = calculate_factorial(4)
print(f"The factorial of 4 is: {result}")
Output: #
The factorial of 4 is: 24
Example: Sum of Numbers in a List (Advanced) #
Let’s build a function that calculates the sum of all numbers inside a list without using a for loop or the built-in sum() function.
def recursive_sum(numbers):
# Base case: If the list is empty, return 0
if not numbers:
return 0
# Recursive case: Add the first item to the sum of the remaining items
else:
return numbers[0] + recursive_sum(numbers[1:])
raw_data = [10, 20, 30, 40]
total_sum = recursive_sum(raw_data)
print(f"List items: {raw_data}")
print(f"Sum calculated via recursion: {total_sum}")
Output: #
List items: [10, 20, 30, 40] Sum calculated via recursion: 100
Challenge Questions for Practice #
Test your problem-solving skills with these recursive exercises:
Challenge 1: Recursive String Reverser #
Write a recursive function called reverse_string(text). The base case should check if the string is empty or has only one character. The recursive case should take the last letter and combine it with the reversed version of the rest of the string. Test it with "Python".
Challenge 2: Geometric Power Calculator #
Create a recursive function called calculate_power(base, exponent). The base case should check if the exponent is 0, and if so, return 1 (since x0=1). The recursive case should return the base multiplied by the power of the exponent decreased by 1. Calculate the value of 2 to the power of 4.
Challenge 3: Fibonacci Sequence Generator #
In the Fibonacci sequence, each number is the sum of the two preceding ones: 0,1,1,2,3,5,8,…. Write a recursive function called get_fibonacci(n) that returns the n-th Fibonacci number. (Hint: You will need two base cases: for n == 0 return 0, and for n == 1 return 1).
