smartyfy.mrindigi.com

Python Master Course V2 — 058. Recursion and Base Cases

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 06 · LESSON 058 / 200

Recursion and Base Cases

Estimated study: 60–90 minutes. Prerequisite: Lesson 57, plus Python variables, collections, conditions and loops.

Course hub

Video lesson

Video not yet available. This is a reserved video link/player location.

Learning objectives

Write and reason about terminating recursive functions. Explain the concepts in your own words, implement the pattern, predict output, test boundary conditions, and refactor for readability.

Concepts and professional approach

Write and reason about terminating recursive functions. A function creates a reusable abstraction: it accepts inputs, performs a focused responsibility, and may return an output. Prefer small named functions with clear contracts. Validate external inputs at system boundaries, choose meaningful names, and separate calculation from printing so functions can be tested. Avoid hidden state where possible. Study the example, then change the inputs and explain the result.

Professional design checklist: define the purpose; choose inputs and outputs; consider invalid and edge-case values; write a minimal implementation; test normal, boundary and failure paths; then document the contract.

Understand and apply: Recursion and Base Cases

A recursive solution needs a smaller problem

Recursion occurs when a function calls itself, directly or indirectly. It fits problems naturally described in terms of smaller versions of themselves, such as nested trees. A correct recursive design needs a base case with an immediate answer, a recursive step that makes measurable progress toward it, and a way to combine the smaller answer. Merely writing a base case does not guarantee termination if the next call moves away from it.

For factorial, the mathematical domain in this lesson is nonnegative integers: zero factorial is 1, and a positive integer factorial multiplies that integer by the factorial of the previous integer. The function below deliberately accepts only built-in int values and rejects bool, even though bool is an int subclass. Negative integers raise ValueError; fractional values, strings, and booleans raise TypeError. Type validation happens before comparisons or subtraction.

Python code

def factorial(n):
    if type(n) is not int:
        raise TypeError("n must be an integer, not a boolean")
    if n < 0:
        raise ValueError("n must be nonnegative")
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(0))
print(factorial(1))
print(factorial(5))
assert factorial(3) == 6

Expected output

1
1
120

Trace calls down and results back up

For factorial(3), the outer call cannot finish its multiplication until factorial(2) returns. That call waits for factorial(1), which returns 1 immediately. The waiting factorial(2) call then computes 2 times 1 and returns 2. Finally factorial(3) computes 3 times 2 and returns 6. Each active call has its own local n. The calls do not share one variable that is repeatedly overwritten.

The number decreases by one and cannot move past the base case for valid inputs, which explains mathematical termination. Python still has a recursion-depth limit, and available call depth depends on the surrounding program. A sufficiently large nonnegative integer may raise RecursionError rather than finish. Do not teach a fixed largest safe input or increase the limit as the routine solution. Python does not eliminate these recursive calls for you.

Python code

def factorial_iterative(n):
    if type(n) is not int:
        raise TypeError("n must be an integer, not a boolean")
    if n < 0:
        raise ValueError("n must be nonnegative")
    result = 1
    for factor in range(2, n + 1):
        result *= factor
    return result

print(factorial_iterative(5))

Expected output

120

The loop uses no growing chain of Python function calls, so it avoids that particular limit. Both versions still spend time performing multiplication, and the resulting integer itself consumes more memory as n grows. Recursion is a clarity tool, not a promise of superior speed or unlimited capacity.

A concrete tree contract

For a folder-like exercise, model each node as a dictionary containing a string name and a list of child nodes. A leaf has an empty children list. Accept trusted, correctly shaped trees only in this starter version. The depth guard below rejects paths deeper than 20 edges; it also ensures a reachable cycle eventually fails rather than recursing forever. A production graph walker would distinguish cycles explicitly, validate the schema, and bound total work.

Python code

def collect_names(node, depth=0):
    if depth > 20:
        raise ValueError("tree is too deep or contains a cycle")
    names = [node["name"]]
    for child in node["children"]:
        names.extend(collect_names(child, depth + 1))
    return names

tree = {"name": "root", "children": [
    {"name": "notes", "children": []},
    {"name": "images", "children": []},
]}
print(collect_names(tree))

Expected output

['root', 'notes', 'images']

Progressive runnable Python example

Requires Python 3.10+. Save as lesson58.py, run with python lesson58.py or python3 lesson58.py.

def factorial(n):
    if type(n) is not int:
        raise TypeError("n must be an integer, not a boolean")
    if n < 0:
        raise ValueError('n must be nonnegative')
    if n <= 1:
        return 1
    return n * factorial(n - 1)
print(factorial(5))
assert factorial(0) == 1
assert factorial(1) == 1
for invalid, error_type in [(1.5, TypeError), (True, TypeError), ("5", TypeError), (-1, ValueError)]:
    try:
        factorial(invalid)
    except error_type:
        pass
    else:
        raise AssertionError(f"accepted invalid input: {invalid!r}")

Expected output:

120

The checks above cover zero and one plus rejection of a fraction, boolean, string, and negative integer. This recursive implementation is intended for small teaching inputs; valid large integers can still exceed available call depth.

Additional exploration

Run the example with different valid inputs. Predict the result before executing. Extract repeated operations into a named function and write at least one assertion for the expected output. For invalid inputs, decide whether to return a documented result or raise an informative exception.

Guided practical project

Implement recursive folder-like tree traversal with a stopping condition. Start with a short requirements table identifying inputs, outputs and validation rules. Implement the smallest working function first, add a separate caller, and test at least three scenarios: typical input, boundary input and invalid input. Print a labeled report only at the program’s outermost layer.

Acceptance criteria: results are deterministic for the same inputs; no unexpected shared mutable state; invalid input is handled deliberately; output is documented; at least three assertions are included in your local project.

Common mistakes and debugging

  • Confusing print with return; printing does not pass a value back to the caller.
  • Using ambiguous names or overly long functions; divide responsibilities clearly.
  • Assuming all inputs are valid; validate values at appropriate boundaries.
  • Relying on global mutable variables; pass dependencies explicitly.
  • Skipping edge-case tests; test zero, empty, negative or missing values as applicable.

Practice and explained answers

Try each question before opening its answer. These self-checks do not record course completion.

Optional hint for question 1

Separate mathematical input validity from whether a call sequence terminates.

1. Why must factorial(1.5) be rejected rather than recursively evaluated?

Answer and reasoning: Ordinary factorial in this lesson is defined for nonnegative integers. Subtracting one from 1.5 eventually reaches a value below 1, but termination alone does not make the resulting number a valid factorial. The type check raises TypeError before recursion.

2. What are the base cases and why is zero included?

Answer and reasoning: Both 0 and 1 return 1 immediately. Zero factorial is 1, matching the empty-product convention and keeping the recurrence consistent. A test for factorial(0) checks a meaningful boundary.

3. Trace factorial(4) after factorial(1) returns.

Answer and reasoning: The pending calls compute 2 × 1 = 2, then 3 × 2 = 6, then 4 × 6 = 24. Returning answers unwinds the chain in the reverse order from the calls.

4. Why might valid factorial input still raise RecursionError?

Answer and reasoning: Mathematical validity does not guarantee enough Python call-stack depth. The recursive implementation adds a call for each step. The iterative version avoids this recursion limit while preserving the same mathematical contract.

5. What happens if a tree node contains itself in its children?

Answer and reasoning: Each recursive step revisits that node at a greater depth. In this starter implementation, depth 21 triggers ValueError. The message permits either excess depth or a cycle; it does not prove which occurred. An active-path identity set would be needed for explicit cycle detection.

Mastery checkpoint

Before moving on, explain the lesson concept, run the example, complete the project, write three tests, and explain why your function design is maintainable. The five-question self-check above provides answer explanations; it does not store account-level completion.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.