Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

What is a Recursive Call?

Recursion refers to a function calling itself.

This technique is commonly used to define mathematical functions such as factorials and Fibonacci sequences.

Factorial Recursive Function Example
def factorial(n):
if n == 0: # Base case
return 1 # Recursion ends
else: # Recursive call
return n * factorial(n-1) # Calls itself with n-1 as argument

# Example: Calculating factorial of 5
factorial_result = factorial(5)

print("factorial_result:", factorial_result) # factorial_result: 120

Recursive functions are useful for solving complex problems by breaking them down into simpler, repetitive tasks.


Base Case

Every recursive function requires a termination condition, called the base case. It defines when the recursion stops.

For instance, in the factorial function above, the statement if n == 0 is the base case that ends the recursion.

This condition ensures that when n reaches 0, the function stops calling itself, preventing infinite recursion.


Pros and Cons of Recursion

Pros:

  1. Simplifies code, making it more readable and intuitive.

  2. It allows complex problems to be expressed concisely.

  3. It is particularly useful for implementing data structures like trees and graphs.


Cons:

  • Recursive calls require additional memory, which can lead to higher usage.

  • If not implemented correctly, it can lead to infinite loops.