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.

def factorial(x):
    if x == 1:
        return 1
    else:
        return x * factorial(x-1)
print(factorial(5)) 

if you run it, you get:

 >>>
120

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.

def is_even(x):
    if x == 0:
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    return not is_even(x)

print(is_odd(23))
print(is_even(23)) 

if you run it, you get

>>>
True
False

⇐ Go to Python Lesson 6.5 – Decorators

Go to Python Lesson 6.7 – Sets ⇒

Leave a Reply