This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Recursion, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What must every recursive function have?
Answer: A base case
Why: Without a base case, the function keeps calling itself.
What is printed?
def f(n):
if n == 0:
return 1
return n * f(n - 1)
print(f(4))Answer: 24
Why: The calls multiply 4 * 3 * 2 * 1, which is 24.
Why can a recursive function raise RecursionError?
Answer: It never reaches a base case
Why: Each call adds a frame until Python's recursion limit is exceeded.
What is the output?
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(5))Answer: 5
Why: fib(5) follows the sequence 0, 1, 1, 2, 3, 5.
Complete the base case.
def factorial(n):
if n <= 1:
____ 1
return n * factorial(n - 1)
print(factorial(3))Answer: return
Why: The base case returns 1 without making another call.
Complete the smaller input.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n ____ 1)
print(factorial(4))Answer: -
Why: factorial(n - 1) moves one step closer to the base case.
Complete the base value for an empty list.
def total(items):
if not items:
return ____
return items[0] + total(items[1:])
print(total([1, 2]))Answer: 0
Why: An empty list contributes nothing to the total.
Complete the second recursive call.
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - ____)
print(fib(5))Answer: 2
Why: fib(n) calls fib(n - 1) and fib(n - 2).
What does this code print?
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(3))Answer: 6
Why: 3 * 2 * 1 is 6.
What does the program output?
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
print(total([2, 4, 6]))Answer: 12
Why: The recursive calls add 2 + 4 + 6, which is 12.
What appears on the screen?
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(6))Answer: 8
Why: The sequence reaches 8 at index 6.
What is printed?
def countdown(n):
if n == 0:
return 0
return 1 + countdown(n - 1)
print(countdown(4))Answer: 4
Why: The function counts four steps back to zero.
Try the questions first
Open the practice page for Python Recursion and answer the same 12 questions with instant feedback.