Python Calculate Factorial of a Given Number

Document 对象参考手册Python3 Examples

Factorial is a mathematical concept. The factorial of a positive integer n is the product of all positive integers less than or equal to n, denoted as n!. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The following is a Python function that calculates the factorial.

Example

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Test the function
number = 5
print(f"The factorial of {number} is {factorial(number)}")

Code explanation:

  1. def factorial(n):Defines a function namedfactorialthat accepts a parametern。
  2. if n == 0 or n == 1:Checknwhether it is 0 or 1; if so, return 1, because both 0! and 1! equal 1.
  3. else:Ifnis not 0 or 1, then recursively callfactorial(n - 1)and multiply bynuntilnit decreases to 1.
  4. number = 5Set a variablenumberto 5 to test the function.
  5. print(f"The factorial of {number} is {factorial(number)}")Print the factorial result of 5.

Output result:

The factorial of 5 is 120

Document 对象参考手册Python3 Examples

Other Extensions