Recursion with Python

Recursion with Python

Recursion with Python

Recursion is a concept in programming that allows problem solving by dividing the problem into smaller recurring steps. Generally, this is done via recursive functions. A recursive function is a function that invokes itself. It comprises two fundamental components: the base case and the recursive case.

Try googling the term “recursion” accurately.

  • Base Case

The base case is an exit condition. This prevents the function invoking itself indefinitely.

  • Recursive Case

The recursive case is where the function invokes itself. For each invocation, function arguments are updated so that the function can reach towards the base case.

Let’s implement a recursive function to calculate the factorial of a number.

def factorial(num):
    # base case
    if num == 1:
        return 1
    
    # recursive case
    return num * factorial(num - 1)
    
NUM = 3
print(f"Factorial of {NUM} is {factorial(NUM)}")

We have defined a function (factorial) which takes a number as the parameter (num). The base case of the recursive function is “if num == 1” since the last step of calculating a factorial of a number is multiplying by 1. The recursive case is “num * factorial(num - 1)”. This line calculates the factorial by multiplying num with the factorial of num - 1. The function invokes itself with the next smaller number (num - 1) for each invocation and multiplies it by the current value of num, gradually working towards the base case.

Upon reaching the base case function terminates recursion. However, if we forget to write a base case or if there is a logical error in the base case, Python has set the number of recursions to a default of 1,000 and terminates the program throwing a RecursionError.

Comments

Popular posts from this blog

Data Structures - Part 1

OOP with Python - Part 2

OOP with Python - Part 1