Python Compute Factorial Using Recursion
A factorial is a mathematical concept: the product of multiplying all integers from 1 up to a positive integer n. For example, the factorial of 5 (written 5!) is 1 * 2 * 3 * 4 * 5 = 120. We can compute a factorial using recursion, a technique in which a function calls itself.
Example
def
factorial
(
n
)
:
if
n
==
1
:
return
1
else
:
return
n * factorial
(
n -
1
)
Compute the factorial of 5
result
=
factorial
(
5
)
(
result
)
Code analysis:
factorialThe function is a recursive function that takes an integernas its argument.- If both the
nequals 1, the function returns 1; this is the termination condition of the recursion. - Otherwise, the function returns
nmultiplied byfactorial(n - 1), that is, the factorial ofnmultiplied byn-1. - At the end of the code we call
factorial(5)to compute the factorial of 5 and print the result.
Output result:
120
Python3 Examples