Code

A Function That Calls Itself

A recursive function solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs two parts:

  1. A base case: a version so small you can answer it directly.
  2. A recursive case: shrink the problem a little, call yourself, and use the answer.
def factorial(n):
    if n <= 1:                   # base case
        return 1
    return n * factorial(n - 1)  # recursive case

print(factorial(4))  # 4 * 3 * 2 * 1 = 24

Think of it as a promise: "Give me factorial(3) and I can make factorial(4)." Python stacks up these promises until it reaches the base case. Then it multiplies its way back out.

Pip tip: Each recursive call must move closer to the base case. Otherwise it calls itself forever.

Assignment

Use recursion (no loops) for both:

  1. lantern_sum(n) returns n + (n-1) + ... + 1. For n <= 0 it returns 0.
  2. power(base, exp) returns base raised to exp (a whole number >= 0) without using ** or pow. Remember: anything to the power 0 is 1.