Use of recursion for repetitive algorithms

--Originally published at Programming Fundaments

In this topic we need to define “recursion” this means to “run back” or to retunr to itself. For this topic we are going with some factorials. and what we want to acomplish is to avoid infinite loops. to explain it better:  Recursion in computer science is a method where the solution to a problem is based on solving smaller instances of the same problem. Example:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

Then we add a couple of prints to the previous funtion

def factorial(n):
    print("factorial has been called with n = " + str(n))
    if n == 1:
        return 1
    else:
        res = n * factorial(n-1)
        print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
        return res	

print(factorial(5))

Giving the next result:

factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for  2  * factorial( 1 ):  2
intermediate result for  3  * factorial( 2 ):  6
intermediate result for  4  * factorial( 3 ):  24
intermediate result for  5  * factorial( 4 ):  120
120

Examples and more at: http://www.python-course.eu/recursive_functions.php