6.4.3 Classic Recursive Patterns

Unit: Unit 6: Functions • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Part 1: Recursive Factorial (n! = n * (n - 1)!)
def factorial(n):
    if n <= 1:
        return 1  # Base Case: 0! = 1 and 1! = 1
    return n * factorial(n - 1)  # Recursive Step

# Part 2: Recursive Sum of a List
def recursive_sum(numbers):
    if not numbers:
        return 0  # Base Case: sum of an empty list is 0
    # Head + sum of Tail
    return numbers[0] + recursive_sum(numbers[1:])

print("5! =", factorial(5))
print("Sum of [10, 20, 30, 40]:", recursive_sum([10, 20, 30, 40]))
Open in Live Interactive Python Sandbox →