Hello! Welcome back to our module on recursion.
In the last lesson, we introduced the core concepts of recursion. We learned that every recursive function has two essential parts: a base case, which is the simple stopping condition, and a recursive step, where the function calls itself with an input that moves it closer to the base case. We used the factorial function to understand this conceptually.
Today, we'll build on that foundation. Your learning outcome is to implement a simple recursive function, such as factorial. We'll move from theory to practice, translating the recursive definition of a factorial directly into working Python code.
From Mathematical Definition to Python Code
Let's quickly recall the recursive definition of the factorial function, n!:
- Recursive Step:
n! = n * (n-1)!(forn > 1) - Base Case:
1! = 1
This structure, with a rule for the general case and a separate rule for the stopping case, maps perfectly to an if/else statement in Python.
Let's watch a short video that walks through how to write the Python code for this.
Factorial Using Recursion in Python | 33
This video from Telusko provides a clear, step-by-step demonstration of implementing the factorial function recursively in Python. Focus on how the mathematical logic translates into the function's structure.
Watch the segment from 02:31 to 04:47. Pay close attention to how the if statement is used for the base case and how the return statement in the else block makes the recursive call.
As you saw in the video, the implementation is surprisingly concise. Here's the code, which you can now write and understand:
def factorial(n):
# Base Case: If n is 1, we know the answer directly.
if n == 1:
return 1
# Recursive Step: For any other number, we apply the recursive formula.
else:
return n * factorial(n - 1)
# Let's test it
result = factorial(5)
print(result) # Output: 120
This function is a perfect demonstration of the recursive pattern: a simple if/else block that separates the stopping condition from the part that breaks the problem down further.
A Method for Creating Recursive Functions
Writing your first recursive function can feel a bit like magic. How can you use a function that you haven't even finished writing yet? To help demystify this, programmers often use a mental trick called the "recursive leap of faith."
The idea is to trust that your function will "just work" for the smaller sub-problem, and then use that result to solve your current problem. The following article outlines a fantastic, structured set of guidelines based on this idea.
The Recursive Leap of Faith, Explained
This article, 'The Recursive Leap of Faith, Explained' by Al Sweigart, provides a five-step method for designing recursive functions. It gives you a reliable process to follow.
Read the section that starts with 'Then let's apply the following guidelines' and ends just before 'Second Caveat: The argument to the recursive function call must ALWAYS get closer to the base case.' Focus on understanding guidelines 1, 2, 3, and the 'First Caveat'.
Let's summarize those key guidelines and apply them to the factorial function we just wrote:
- Figure out the data types:
factorialtakes an integer (number) and returns an integer (the result). - Implement the base case: The simplest case is
factorial(1), which should return1. This becomes ourif n == 1: return 1. - Take the leap of faith for the recursive case: We assume that
factorial(n - 1)will magically return the correct value for(n-1)!. - Use the result of the recursive call: How do we get from
(n-1)!ton!? We multiply byn. This gives us our recursive step:return n * factorial(n - 1).
This methodical approach—defining the base case, then assuming the recursive call works for a smaller case and using its result—is a powerful way to design recursive algorithms without getting lost in the details.
Your Turn: Tracing the "Magic"
Now that you've seen how to write the function, let's explore what's happening under the hood. A great way to visualize a recursive function's execution is to add print() statements to trace its flow.
Here is an embellished version of the factorial function. Before running it, can you predict what the output will be for factorial(3)?
def factorial_trace(n):
print(f"Calling factorial_trace with n = {n}")
# Base Case
if n <= 1:
print(f"Base case reached. Returning 1.")
return 1
# Recursive Step
else:
# We take the "leap of faith" here. Assume this call works.
recursive_result = factorial_trace(n - 1)
# Now we use the result from the smaller sub-problem.
result = n * recursive_result
print(f"Returning from call with n = {n}. The result is {result}.")
return result
# Let's run it!
print("\nFinal Result:", factorial_trace(3))
Running the Code
Copy the code above into your Python environment and run it. Your output should look like this:
Calling factorial_trace with n = 3
Calling factorial_trace with n = 2
Calling factorial_trace with n = 1
Base case reached. Returning 1.
Returning from call with n = 2. The result is 2.
Returning from call with n = 3. The result is 6.
Final Result: 6
Notice the pattern: the calls go "down" (n=3, n=2, n=1) until the base case is hit. Then, the returns happen "upwards" as each waiting call uses the result from the one below it.
This image provides a great diagram of this exact process for factorial(3).

Conclusion
Great job today! You have successfully moved from understanding the theory of recursion to implementing a real recursive function in Python. This is a major step in developing your algorithmic thinking.
Key Takeaways:
- A recursive function's structure directly mirrors its logical definition, typically using an
if/elseblock to separate the base case from the recursive step. - The "Recursive Leap of Faith" is a powerful mental model: trust that the recursive call on a smaller problem works, and use its result to solve the current problem.
- You can use
print()statements to trace the execution of a recursive function, revealing the pattern of calls descending to the base case and results returning back up.
Preview of the Next Lesson:
Our print-tracing gave us a glimpse into how the computer manages all those nested function calls. In the next lesson, we will formalize this by learning about the call stack. Understanding the call stack is the key to mastering recursion, as it explains exactly how the computer keeps track of where it is, what values it's working with, and where it needs to go next.