Recursion in Python

Tram Ho

Hello everyone In this article, I will introduce you to the concept of Thread Rules in Python. You all find out in my article!

What is recursion?

Recursion means that a function calls itself back.

An example of t is to place two parallel mirrors facing each other. Any object in between them will be reflected called recursion.

Recursive Functions in Python

In Python, we know that one function can call other functions. It is even possible for the function to call itself. These types of structures are called recursive functions.

The following image shows the operation of a recursive function called the recurse . The following is an example of a recursive function to find the factorial of an integer.

The factorial of a number is the product of all integers between 1 and that number. Example: the factorial of 6 (denoted by 6!) Is 1*2*3*4*5*6 = 720

Example of a recursive function

The result will be

In the example above factorial() is a recursive function because it calls itself.

When we call this function with a positive integer, it recursively calls itself by decrementing the number

Each function multiplies the number by the factorial of the number below it until it equals one. How to call this recursive function can be explained in the following steps.

Here’s an image that explains step-by-step how to treat recursive functions: Our recursion ends when the number drops to 1. This is called a mandatory condition.

Note that every recursive function must have a condition that is required to stop recursion otherwise the function calls itself indefinitely.

By default, the maximum depth of recursion is 1000 . If the limit is passed, it results in a RecursionError error.

Below is an example where the depth limit is exceeded.

The error will display as follows:

1. When using the Recursive function, the code will be cleaned and optimized.
2. A complex request can be broken down into smaller, simpler tasks using recursion.