Recursive Functions

Recursive Factorial

def factorial(n):
    if (n<0): # Termination condition
        print("Invalid input")
    elif (n == 0 or n == 1):  # Termination condition
        return 1
    else:
        return n * factorial(n-1) # Recursive Call


print(factorial(8))

	

The recursive flow of execution of the factorial function (fact for short) for n = 4 is as follows:


4. fact(4) = 4 * fact(3)
3.                |-> fact(3) = 3 * fact(2)
2.                                   |-> fact(2) = 2 * fact(1)
1.                                                       |-> fact(1) = 1