Python Lessons – 6.6 Recursions

Python Lesson - 6.6 Recursions

Recursions

Recursion is a very important concept in functional programming.

A basic aspect of recursion is the self-reference of the function that calls itself.

A classic example of a recursively implementable function is the factorial function. The factorial of a number is equivalent to the product of all the numbers from 0 up to that specified number.

if you run it, you get:

From the code above you can see that we have an if condition that differentiates two different cases, when to use recursion and when not to use it. The case in which the recursion is not used is called base case, where no recursion is required for the calculation of that step.

The use of recursive functions, if implemented incorrectly (for example without taking into account the base case) are endless and will be interrupted only by the launch of an exception (RunTime Error). So you must always be careful before executing them.

Indirect Recursions

The recursions can also be indirect. A function can call a second one which in turn calls the first one, and so on. But the same thing can happen with more features.

if you run it, you get

⇐ Go to Python Lesson 6.5 – Decorators

Go to Python Lesson 6.7 – Sets ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.