Python Calculate Factorial Using Recursion
Factorial is a mathematical concept that represents the product of multiplying from 1 to a positive integer n. For example, the factorial of 5 (denoted as 5!) is 1 2 3 4 5 = 120. We can use recursion to calculate factorials. Recursion is a technique in which a function calls itself.
Example
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
# Calculate the factorial of 5
result = factorial(5)
print(result)
if n == 1:
return 1
else:
return n * factorial(n - 1)
# Calculate the factorial of 5
result = factorial(5)
print(result)
Code explanation:
factorialThe function is a recursive function that takes an integernas a parameter.- If
nequals 1, the function returns 1, which is the termination condition of the recursion. - Otherwise, the function returns
nmultiplied byfactorial(n - 1)the result of, i.e.,nmultiplied byn-1the factorial of. - At the end of the code, we call
factorial(5)to calculate the factorial of 5 and print the result.
Output result:
120Other extensions
Python3 Examples