Python Recursion Exercises
Python Recursion Practice Questions
Which of the following function definitions shows the correct syntax for writing a recursive function in Python?
This question checks understanding of the syntax rules for recursion in Python:
- Option 1: Correct ✅ – Defines a function with
def, has a base case, and calls itself properly. - Option 2: Incorrect – Missing
returnfor the recursive call; without it, results are lost. - Option 3: Incorrect – Invalid syntax because
n func(n-1)is not a valid expression. - Option 4: Incorrect – Python does not use the keyword
function; it usesdef.
Key takeaway: A recursive function in Python must be defined with def, include a base case, and call itself with valid syntax using return.
Which of the following functions is recursive?
This question checks the ability to recognize a recursive function:
- Option 1: Incorrect – Performs a calculation but does not call itself.
- Option 2: Incorrect – Uses a loop to compute factorial, not recursion.
- Option 3: Incorrect – A simple addition function, no self-calls.
- Option 4: Correct ✅ – The function
countdowncalls itself withn-1, making it recursive.
Key takeaway: A function is recursive if it explicitly calls itself within its definition.
In a recursive function, what is the purpose of the base case?
This question checks the understanding of the base case in recursion:
- Option 1: Incorrect – The base case is not about speed; it is about correctness and termination.
- Option 2: Correct ✅ – The base case defines the condition where recursion stops, preventing infinite calls and stack overflow errors.
- Option 3: Incorrect – Base cases do not change recursion into iteration; they just terminate recursion at the right point.
- Option 4: Incorrect – That refers to memoization, not the base case.
Key takeaway: A base case ensures recursion terminates properly. Without it, the recursive function would run indefinitely and cause a stack overflow.
Which of the following statements about recursion is true?
This question tests the conceptual understanding of recursion:
- Option 1: Incorrect – Recursion is widely used in many areas (tree traversal, sorting, searching), not only math.
- Option 2: Correct ✅ – A recursive function needs a base case (to stop) and a recursive step (to continue until base case is reached).
- Option 3: Incorrect – Recursion is not always faster; in fact, loops are usually more efficient in Python.
- Option 4: Incorrect – Recursion relies heavily on the call stack, where each recursive call is stored until it returns.
Key takeaway: The essential structure of recursion is a base case and a recursive step; missing either leads to incorrect or infinite recursion.
What will be the output of the following recursive function call?
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(4))
This problem tests understanding of recursion with the factorial function:
- Step 1: factorial(4) = 4 * factorial(3)
- Step 2: factorial(3) = 3 * factorial(2)
- Step 3: factorial(2) = 2 * factorial(1)
- Step 4: factorial(1) = 1 * factorial(0)
- Step 5: factorial(0) = 1 (base case)
Now multiplying back:
4 × 3 × 2 × 1 = 24
Correct Answer: Option 4 ✅
Which of the following conditions is essential in every recursive function to prevent infinite recursion?
Every recursive function must include a base case. The base case is the condition that tells the function when to stop calling itself. Without it, the function would continue calling itself endlessly, leading to a RecursionError in Python.
- Option 1: A return statement is important but not enough to stop infinite recursion.
- Option 2: Calling the function twice or more is not necessary for recursion.
- Option 3: Defining a variable outside does not affect recursion control.
- Option 4: Correct. A base case ensures recursion eventually stops.
Correct Answer: Option 4 ✅
In Python, what happens if a recursive function does not have a base case?
In Python, if a recursive function lacks a base case, the function will keep calling itself without stopping. This creates an infinite recursion scenario. However, Python has a built-in recursion depth limit (default is 1000 calls).
- Option 1: Incorrect, because the program cannot run indefinitely; Python will eventually throw an error.
- Option 2: Incorrect, Python does not automatically fix the issue. It just raises an error when the limit is reached.
- Option 3: Correct. Python raises a
RecursionError: maximum recursion depth exceeded. - Option 4: Incorrect, since the function will not terminate after one call without a base case.
Correct Answer: Option 3 ✅
Which of the following is a valid recursive function definition in Python?
A valid recursive function in Python must:
- Call itself inside the function body.
- Include a base case to stop recursion.
Now let’s analyze the options:
- Option 1: Invalid, because it has no base case, leading to infinite recursion.
- Option 2: Incomplete, since it lacks a
returnvalue whenx == 0. - Option 3: Correct. This is a classic factorial implementation using recursion, with a base case (
x == 0). - Option 4: Not recursive at all, because the function does not call itself.
Correct Answer: Option 3 ✅
Which of the following functions correctly calculates the sum of all elements in a list using recursion?
This question tests writing a recursive function to sum elements in a list:
- Option 1: Incorrect – Uses iteration, not recursion.
- Option 2: Correct ✅ – Base case checks for an empty list, then adds the first element to the sum of the rest of the list recursively.
- Option 3: Incorrect – Infinite recursion; no base case and no processing.
- Option 4: Incorrect – Base case is invalid;
lst == 0will never be true for a list.
Key takeaway: For list recursion, always define a base case (empty list) and ensure the function reduces the list size on each recursive call.
Which of the following functions correctly returns the nth Fibonacci number using recursion?
This question tests the correct implementation of the Fibonacci sequence using recursion:
- Option 1: Incorrect – Calls
fib(n)instead offib(n-2), causing infinite recursion. - Option 2: Incorrect – Uses iteration, not recursion.
- Option 3: Correct ✅ – Proper recursive definition: returns
nfor base cases (0 or 1) and adds the previous two Fibonacci numbers for others. - Option 4: Incorrect – Incorrect recursive formula; adds 1 instead of the previous Fibonacci number.
Key takeaway: For Fibonacci recursion, always define proper base cases (0 and 1) and reduce n in each recursive call to avoid infinite recursion.
Which of the following functions correctly finds the maximum element in a list using recursion?
This question tests finding the maximum value in a list using recursion:
- Option 1: Correct ✅ – Base case: when list has one element, return it. Recursive step: find the maximum of the rest of the list and compare with the first element.
- Option 2: Incorrect – Uses Python’s built-in
maxfunction, not recursion. - Option 3: Incorrect – Base case returns 0, does not compare elements, fails for negative numbers.
- Option 4: Incorrect – Only returns the first element, ignoring the rest of the list.
Key takeaway: When using recursion for lists, define a base case for a single element, then combine results from recursive calls to solve the problem incrementally.
Which of the following functions correctly reverses a string using recursion?
This question tests using recursion to reverse a string:
- Option 1: Incorrect – Uses slicing, not recursion.
- Option 2: Correct ✅ – Base case: empty string returns "". Recursive step: reverse the substring excluding the first character and append the first character at the end.
- Option 3: Incorrect – Prints characters in reverse but does not return the reversed string.
- Option 4: Incorrect – Recursive step adds the first character at the start instead of the end, resulting in the original string.
Key takeaway: Recursive string reversal involves taking the first character, reversing the rest of the string recursively, and appending the first character at the end.
Which of the following functions correctly computes the GCD (Greatest Common Divisor) of two numbers using recursion?
This question tests using recursion to compute the GCD using the Euclidean algorithm:
- Option 1: Correct ✅ – Base case: if
b == 0, returna. Recursive step: callgcd(b, a % b). - Option 2: Incorrect – Uses iteration instead of recursion.
- Option 3: Incorrect – Subtracts 1 from both numbers and may not find the correct GCD; also inefficient.
- Option 4: Incorrect – Simply adds numbers; does not compute GCD.
Key takeaway: Recursive GCD relies on the Euclidean algorithm: keep replacing the pair with (b, a % b) until b is 0. The remaining a is the GCD.
Which of the following statements about recursive binary search is true?
This question tests understanding of the concepts behind recursive binary search:
- Option 1: Incorrect – Binary search only works correctly on sorted lists.
- Option 2: Incorrect – Base case is essential to stop recursion when the element is found or the search interval is empty.
- Option 3: Incorrect – Binary search is faster than linear search for large sorted lists; its complexity is O(log n).
- Option 4: Correct ✅ – Recursive binary search requires a sorted list and a base case to terminate the recursion.
Key takeaway: Recursive binary search relies on dividing the search interval in half, checking the middle element, and using a base case to terminate recursion either when the element is found or when the interval becomes empty.
Which of the following functions correctly checks if a string is a palindrome using recursion?
This question tests using recursion to check if a string is a palindrome:
- Option 1: Incorrect – Uses slicing, not recursion.
- Option 2: Correct ✅ – Base case: string of length 0 or 1 is a palindrome. Recursive step: check if first and last characters are equal and recurse on the substring excluding them.
- Option 3: Incorrect – Uses iteration, not recursion.
- Option 4: Incorrect – Does not perform any character checks, always returns True or False incorrectly.
Key takeaway: Recursive palindrome checking compares the first and last characters and reduces the problem size by slicing the string until the base case is reached.
Which of the following functions demonstrates multiple recursive calls correctly?
This question illustrates multiple recursive calls in a function:
- Option 1: Incorrect – Returns n directly, no recursion.
- Option 2: Correct ✅ – Each call to
fib(n)makes two recursive calls:fib(n-1)andfib(n-2). This is a classic example of recursion with multiple recursive branches. - Option 3: Incorrect – Uses a loop instead of proper recursion to calculate Fibonacci.
- Option 4: Incorrect – Recursive call
fib(n)calls itself without reducing n, leading to infinite recursion.
Understanding the recursion flow:
When you call fib(4), the function executes as:
fib(4)
├─> fib(3)
│ ├─> fib(2)
│ │ ├─> fib(1) = 1
│ │ └─> fib(0) = 0
│ └─> fib(1) = 1
└─> fib(2)
├─> fib(1) = 1
└─> fib(0) = 0
Finally, all these return values are added together to compute fib(4) = 3.
Key takeaway: Multiple recursive calls occur when a function calls itself more than once in the same call. Understanding the call tree helps visualize how recursion works step by step.
Which of the following functions is an example of tail recursion?
This question explains tail recursion vs normal recursion:
- Option 1: Incorrect – Normal recursion; the multiplication happens after the recursive call returns, so it is not tail recursion.
- Option 2: Incorrect – Normal recursion with addition after returning from recursion; not tail recursion.
- Option 3: Correct ✅ – Tail recursion; the recursive call is the last operation, and all necessary computation is passed through the accumulator
acc. - Option 4: Incorrect – Fibonacci recursion involves multiple recursive calls and is not tail recursion.
Understanding Tail Recursion:
In tail recursion, the recursive call is the last operation of the function. This allows some languages to optimize recursion and reuse the same stack frame. Although Python does not optimize tail recursion, understanding the concept is important for algorithm design.
Example flow for factorial_tail(4):
factorial_tail(4, 1) → factorial_tail(3, 4) → factorial_tail(2, 12) → factorial_tail(1, 24) → factorial_tail(0, 24) → returns 24
Key takeaway: Tail recursion passes all necessary computation through parameters and allows the recursive call to be the last operation.
Which of the following functions correctly calculates the sum of all elements in a nested list using recursion?
This question tests recursion over nested lists:
- Option 1: Incorrect – Works only for flat lists, fails on nested lists.
- Option 2: Incorrect – Uses built-in
sum, no recursion. - Option 3: Incorrect – Works only for flat lists; does not check for nested lists.
- Option 4: Correct ✅ – Checks each element: if it is a list, recursively calculates its sum; otherwise adds the element to total.
Understanding the recursion:
When encountering a nested list like [1, [2, 3], 4]:
sum_nested([1, [2, 3], 4]) → 1 + sum_nested([2, 3]) + 4 → 1 + (2 + 3) + 4 → 10
Key takeaway: Recursive functions can handle arbitrarily nested structures by checking the type of each element and recursing only when needed.
Which of the following statements correctly describes recursive backtracking?
This question tests understanding of recursion in backtracking algorithms:
- Option 1: Incorrect – Recursive backtracking explores possibilities in a depth-first manner; it may not find the shortest path first.
- Option 2: Incorrect – A base case is required to stop recursion at dead-ends or when the goal is reached.
- Option 3: Correct ✅ – Recursive backtracking explores all possibilities. It goes deeper recursively, and when a path leads to a dead-end, it backtracks to try alternative paths.
- Option 4: Incorrect – Backtracking is applicable to puzzles, strings, grids, and combinatorial problems, not just numbers.
Understanding recursive backtracking:
For example, navigating a maze:
1. Start at the entrance. 2. Move to a possible next step recursively. 3. If the path leads to a dead-end, return (backtrack) to the previous step and try another path. 4. Repeat until the exit is found or all paths are exhausted.
Key takeaway: Recursive backtracking is powerful for exploring all options systematically, using recursion to manage the current path and backtracking to previous states when needed.
Why is recursion often used in programming?
This question wraps up the key concept of recursion:
- Option 1: Incorrect – Recursion is not always faster than iteration; sometimes it is slower due to function call overhead.
- Option 2: Incorrect – Every recursive function requires a base case to terminate properly.
- Option 3: Incorrect – Recursion can use extra memory due to the call stack, especially for deep recursion.
- Option 4: Correct ✅ – Recursion is a natural fit for problems that can be divided into smaller sub-problems, such as factorials, Fibonacci numbers, tree traversal, and combinatorial problems.
Key takeaway: Recursion allows programmers to solve complex problems by defining a function in terms of itself. By focusing on smaller sub-problems and using base cases to terminate, recursion can simplify code readability and logic, especially for hierarchical or divide-and-conquer problems.
Explore More Python Exercises
You may also like these Python exercises:
Test Your Python Recursion Knowledge
Practicing Python Recursion? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – Recursion
Recursion is one of those concepts in Python that feels tricky at first, but once it clicks, it changes the way you think about problem-solving. In this section on Solviyo, we’ll walk through practical exercises that will help you understand recursion from the ground up and use it effectively in your own code.
At its core, recursion simply means a function calling itself. That may sound strange at first, but it’s actually a powerful way to break down problems into smaller, repeatable steps. We’ll start with the basics, like writing a recursive function for factorial or Fibonacci numbers, so you can clearly see how recursion works step by step.
Once you’re comfortable with the idea, we’ll move into exercises that show why recursion is so useful. You’ll practice solving problems that naturally fit recursion, such as traversing directories, working with nested lists, or implementing divide-and-conquer algorithms. These aren’t just theory problems—they’re the kind of challenges that sharpen your ability to think like a programmer.
A big part of recursion is knowing how to stop it. That’s where base cases come in. Without them, your function will keep calling itself forever. Through these exercises, you’ll get plenty of practice writing solid base cases, making sure your recursive solutions are both correct and efficient. We’ll also highlight common mistakes, like infinite recursion or stack overflow, so you can recognize and avoid them early on.
Another focus of this section is comparing recursion with iteration. Sometimes recursion gives you a cleaner, more elegant solution, but in other cases, loops are the better choice. By practicing both, you’ll develop the intuition to pick the right approach for the problem at hand.
To keep things practical, we’ll include exercises where recursion is used in real-world ways. For example, breaking down mathematical expressions, exploring tree structures, or even solving puzzles like the Tower of Hanoi. These examples will show you how recursion moves beyond classroom exercises and into real programming challenges.
At Solviyo, we believe practice is the best teacher. That’s why our recursion exercises are structured to guide you step by step, from simple to challenging, with clear explanations along the way. By the time you finish this section, recursion will no longer feel intimidating—you’ll see it as one more tool in your Python toolkit, ready to use whenever a problem calls for it.