Python Recursion Function

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?
Ans: A function calling itself to solve a problem.
Q 2: What is a base condition?
Ans: It stops the recursive calls.
Q 3: What happens if there is no base condition?
Ans: It causes infinite recursion.
Q 4: Is recursion memory-intensive?
Ans: Yes, it uses more memory due to function calls.
Q 5: When should recursion be used?
Ans: When a problem can be divided into smaller sub-problems.

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)?






Related Python Recursion Function Topics