Recursive Function in Python
What is a Recursive Function? A recursive function is a function that calls itself to solve a smaller version of the same problem.
Usually, recursion has two parts:
- Base Case – stops the recursion to prevent infinite calls.
- Recursive Case – the function calls itself with modified arguments.
Syntax of a Recursive Function
def function_name(parameters):
if base_condition:
return some_value # Base case
else:
return function_name(modified_parameters) # Recursive case Example: Factorial of a Number.
Python
# Recursive function to calculate factorial
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n * factorial of (n-1)
return n * factorial(n - 1)
# Test the function
print(factorial(5)) # Output: 120 Explanation:
- factorial(5) calls factorial(4) → factorial(3) → … until factorial(1).
- Then it multiplies back: 1 → 2 → 6 → 24 → 120.