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:

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: