Python Calculate Factorial Using Recursion

Document 对象参考手册Python3 Examples

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)

Code explanation:

  • factorialThe function is a recursive function that takes an integernas a parameter.
  • Ifnequals 1, the function returns 1, which is the termination condition of the recursion.
  • Otherwise, the function returnsnmultiplied byfactorial(n - 1)the result of, i.e.,nmultiplied byn-1the factorial of.
  • At the end of the code, we callfactorial(5)to calculate the factorial of 5 and print the result.

Output result:

120

Document 对象参考手册Python3 Examples

Other extensions