Python math.factorial() function


The math.factorial() function in Python is used to compute the factorial of a non-negative integer. The factorial of a number nn (denoted as n!n!) is the product of all positive integers from 1 to nn. By definition, the factorial of 0 is 1.

Syntax

import math result = math.factorial(n)
  • n: A non-negative integer for which you want to compute the factorial.

Return Value

  • Returns the factorial of n, which is of type int.
  • Raises a ValueError if n is a negative integer.

Examples

  1. Calculating the factorial of a positive integer:

    import math result = math.factorial(5) print(result) # Output: 120 (because 5! = 5 × 4 × 3 × 2 × 1)
  2. Calculating the factorial of zero: The factorial of 0 is defined as 1.

    result = math.factorial(0) print(result) # Output: 1
  3. Calculating the factorial of a larger number:

    result = math.factorial(10) print(result) # Output: 3628800 (because 10! = 10 × 9 × 8 × ... × 1)
  4. Handling negative integers: Attempting to calculate the factorial of a negative integer will raise a ValueError.

    try: result = math.factorial(-3) except ValueError as e: print(e) # Output: factorial() not defined for negative values

Summary

  • The math.factorial() function computes the factorial of a non-negative integer.
  • It returns an integer representing the factorial value.
  • The function handles the case of zero by returning 1.
  • An error is raised for negative integers, making it a robust choice for calculating factorials. This function is particularly useful in combinatorics, probability, and various mathematical computations.