Python

Recursion In Python – Detailed FAQ

If a function calls itself, it is said to be recursive. For instance, suppose we had a function called abc() that calls the abc variable in its body ().

example of recursion in Python
Here, we are creating a user-defined function called factorial (). This function calculates the factorial of an integer by continuously invoking itself up until the base case, which will be covered in greater detail after this example.

 Example of recursion in Python to
# find the factorial of a given number

def factorial(num):
    """This function calls itself to find
    the factorial of a number"""

    if num == 1:
        return 1
    else:
        return (num * factorial(num - 1))


num = 5
print("Factorial of", num, "is: ", factorial(num))

Output:

Factorial of 5 is:  120

Lets see what happens in the above example:

factorial(5) returns 5 * factorial(5-1) 
    i.e. 5 * factorial(4)
               |__5*4*factorial(3)
                      |__5*4*3*factorial(2)
                           |__5*4*3*2*factorial(1)

A base example for which we already know the value of factorial is factorial(1). The following code defines the base case in the function body:

if num == 1:
    return 1

What is a recursion base case?

When using recursion, we should establish a base case for which we are already aware of the solution. Since we now know that the factorial of 1 is 1, our starting point in the example above is to find the factorial of an integer number.

The function should become closer to the base case with each subsequent recursive call, which is exactly what we are doing in the example above.

In recursive functions, base case is used to ensure that when base case is reached, the function stops calling itself. The function would perpetually call itself without the basic case.

Why do programmers employ recursion?

Recursion is used to divide large issues into smaller ones, which are then divided into yet smaller ones, and so on. In the end, finding answers to all of the smaller subproblems contributes to solving the larger primary problem.

The benefits of recursion

1. Easier to write with recursion.
2. Readable – It’s simpler to read and comprehend code.
3. Reduce the number of lines of code required – Recursion uses fewer lines of code to solve an issue.

Negative aspects of recursion

1. Recursion cannot be used to fix all issues.
2. The code would continue endlessly if the basic case wasn’t defined.
3. Because recursive functions call themselves repeatedly, it is challenging to identify which call is problematic when debugging them.
4. Memory use – Recursive function calls are not memory-efficient.

Related Articles

Leave a Reply

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

Back to top button