Python OOPs


Python SQLite


Examples


Others


Python Recursion


Recursion is a programming technique where a function calls itself to solve smaller instances of a problem. A recursive function must have a base case to prevent infinite recursion and a recursive case where the function calls itself.

Components of Recursion:
  • Base Case: The condition under which the recursion stops.
  • Recursive Case: The logic in which the function calls itself with a reduced or simpler problem.
Example
def factorial(n):
    if n == 0:  # Base case
        return 1
    else:       # Recursive case
        return n * factorial(n - 1)

# Test the function
print(factorial(5))  # 120

Points to create recursive functions

  1. Clearly define the base case.
  2. Ensure the recursive step progresses toward the base case.
  3. Use recursion for problems that naturally fit recursive solutions.
  4. Consider iterative alternatives for performance-critical tasks.