Python factorial() Method Tutorial

Python provides factorial() method in order to calculate factorial of provided number. The mathematically factorial calculation consists of multiple steps which change according to the provided number. Things get complicated as the number gets bigger. But the math.factorial() method can be used to calculate factorial without using naive way.

Calculate Factorial Using Naive Method

The factorial calculation can be done with the naive method or by implementing the factorial formula as an algorithm. The for loop is used with the range() method in order to implement it.


for i in range(1,n+1):
   factorial = factorial*i

print("Factorial of ",n," is ",factorial)

Calculate Factorial Using math.factorial() Method

Python provides the factorial() method via math module for factorial calculations. The syntax of the factorial is very simple where a single number is provided to calculate its factorial. But first, the math module should be imported.

import math

factorial = math.factorial(13)

print("Factorial of 13 is ",factorial)

Calculate Negative Number Factorial

Negative numbers factorial can not be calculated so what will happen if we provide a negative number to the factorial() method. It raises a “Runtime Error” which says “ValueError: factorial not defined for negative values“.

import math

factorial = math.factorial(-13)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: factorial() not defined for negative values

Calculate Floating Point Number Factorial

Factorial is a mathematical calculation that is defined for integers and can not be used for floating-point or non-integer numbers. If we provide a negative number to the factorial() method it raises an error like below.

import math

factorial = math.factorial(4.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: factorial() only accepts integral values

Calculate String Value Factorial

The factorial method can be used for positive and integer numbers. But how can we calculate string values which are numbers? Before using the factorial method we should convert the string into the integer type with the int() method.

import math


factorial = math.factorial(int(str))

Leave a Comment