Skip to content

Nov 15: Recursive Functions

Learning Objectives

After today's class, you should be able to:

  • Identify the base case and recursive step of the factorial function.
  • Trace a recursive function by hand to predict the number of calls.
  • Write short recursive functions based on mathematical sequences.

Announcements

POGIL Activity

  • Recursive Functions
    • If you are absent today, complete this activity at home
    • Bring your completed activity to class or office hours

Model 1

factorial.py
1
2
3
4
5
6
7
8
9
def factorial(n):
    # base case
    if n == 0:
        return 1
    # general case
    product = 1
    for i in range(n, 0, -1):
        product *= i
    return product

Model 2

fibonacci.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def fibonacci(n):
    # base case
    if n == 1 or n == 2:
        return 1
    # general case
    return fibonacci(n - 1) + fibonacci(n - 2)

if __name__ == "__main__":
    for i in range(1, 6):
        print(fibonacci(i))