Recursion

--Originally published at Python

Recursion is when you call a function inside of itself. It can be used in several ways, for example, you could create a function that will give you a final result after repeating itself several times, or it could give you several answers, depending on how many times it went through itself. The most common and probably the easiest example to understand on this subject is when writing a program that gives you the factorial of a number.

Code:

num = int(input(“Type a number: “))

def Factorial(num):
if num<=1:
return 1

else:
return num*Factorial(num-1)

print(Factorial(num))

2recursion

If the number is 1 or 0, the function won’t call itself, it will just return 1. If the number is bigger, then the recursion begins. Every time it goes through the else, it multiplies n by the answer to factorial n-1. This answer will depend on the number you get in the new factorial, and it will keep on decreasing until you get to 1, which is when all the previous numbers will start multiplying. These answer will stack up until the program gets to the first time the function was called, and it will return the final answer. It might be confusing at times, but ultimately, it follows this idea.