Recursion is a programming technique where a function calls itself to solve a problem. A recursive function generally has two main components:
1. Base Case: This stops the recursion when a certain condition is met.
2. Recursive Case: This part breaks the problem down into smaller instances of the same problem and makes a recursive call.
Example: recursive function to calculate the factorial of a number
def factorial(n):
# Base case: if n is 1 or 0, return 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output will be 120
Explanation:
The base case is when n == 0 or n == 1, which returns 1.
The recursive case reduces the problem by calling factorial(n-1).
Python Recursion Function – Interview Questions
Q 1: What is recursion in Python?
Q 2: What is a base condition?
Q 3: What happens if there is no base condition?
Q 4: Is recursion memory-intensive?
Q 5: When should recursion be used?
Python Recursion Function – Objective Questions (MCQs)
Q1. What is recursion in Python?
Q2. Which of the following is required in a recursive function to avoid infinite recursion?
Q3. What will happen if a recursive function has no base case?
Q4. What is the output of the following code?
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(4))
Q5. What is the maximum recursion depth by default in Python (approximately)?