VOOZH about

URL: https://www.geeksforgeeks.org/python/factorial-in-python/

⇱ factorial() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

factorial() in Python

Last Updated : 5 Jun, 2026

The factorial of a number n (written as n!) is the product of all positive integers from 1 to n. Example:

5! = 1 * 2 * 3 * 4 * 5 = 120.

Python provides a function math.factorial() that computes factorial without writing the entire loop manually.

Syntax

math.factorial(x)

  • Parameters: x is a number whose factorial is to be calculated (must be a non-negative integer).

Examples of math.factorial()

Example 1: This example uses math.factorial() to compute factorial directly using Python’s inbuilt function.


Output
720

Example 2: This example shows what happens when you pass a negative number to math.factorial(). Python raises a ValueError.

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: factorial() not defined for negative values

Explanation: math.factorial(-3) triggers an error because factorial for negative numbers does not exist.

Example 3: This example demonstrates that factorial only works with integers. Passing a float raises a TypeError.

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Explanation: math.factorial(4.7) rraises an error because fractional factorial values are not supported.

Comment
Article Tags: