What is a recursive function in Python?

What is a recursive function in Python?

a) A function that calls itself
b) A function that returns multiple values
c) A function that takes no arguments
d) A function that runs in a loop

Answer:

a) A function that calls itself

Explanation:

A recursive function in Python is a function that calls itself in its definition. Recursion is a powerful technique used to solve problems that can be broken down into smaller, similar subproblems. It is commonly used in algorithms like searching, sorting, and traversing data structures such as trees and graphs.

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)  # This function calculates the factorial of n recursively

In this example, the factorial() function calls itself with a decremented value of n until it reaches the base case where n equals 1.

Recursion is a powerful tool but should be used carefully to avoid infinite loops and excessive memory usage. It’s important to ensure that a base case is defined to terminate the recursive calls.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top