Skip to content
thesarfo

Note

Recursion Basics

Recursion as a self-calling function, illustrated by computing a factorial both with a loop and with recursion.

views 0

Recursion is a function that calls itself. It creates a pattern of repeating itself over and over. It is like a for loop, but much faster and efficient. Look at the below example of finding the factorial of a number. First using a for loop and then using a recursive function

def factorial_looping(n):
if n < 0:
return 0
else:
factorial = 1
for i in range(1, n+1):
factorial = factorial * i
return factorial
print(factorial_looping(5))
def factorial_recursion(n):
if n == 1:
return 1
else:
return n * factorial_recursion(n - 1)
print(factorial_recursion(5))