12. Recursion
A recursive function is a function that calls itself. Every recursion needs two parts:
- A base case: a condition where the function stops calling itself.
- A recursive case: a call with a smaller or simpler input that moves toward the base case.
Without a base case, the function calls itself forever and Python raises RecursionError.
A recursive function can also return a value. The factorial of n is n * (n - 1) * ... * 1:
factorial(4) is 4 * 3 * 2 * 1 = 24.
Count down recursively
Define countdown(n) that uses an if statement. When n > 0, it prints n and then calls countdown(n - 1). When n is 0, it does nothing. Call countdown(3).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Factorial with recursion
Define factorial(n) that uses an if statement. Return 1 when n <= 1; otherwise return n * factorial(n - 1). Print factorial(5).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Sum numbers recursively
Define sum_to(n) that uses an if statement. Return 0 when n == 0; otherwise return n + sum_to(n - 1). Print sum_to(5).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Recursive power
Define power(base, exponent) that uses an if statement. Return 1 when exponent == 0; otherwise return base * power(base, exponent - 1). Print power(2, 5).
Print exactly:
Create a free account to save your progress and unlock chapter 2.