  factorial () in python

Python Methods and Functions

Not many people know, but Python offers a direct function that can calculate the factorial of a number without writing all the code to calculate the factorial.

A naive method to calculate the factorial

 # Python code to demonstrate the naive method # to calculate the factorial n = 23 fact = 1   for i in range ( 1 , n + 1 ): fact = fact * i   print ( "The factorial of 23 is:" , end = "") print (fact)

Output:

The factorial of 23 is: 25852016738884976640000

Using math.factorial ()

This method is defined in the " math " python module. Since it has an internal C type implementation, it is fast.

math.factorial (x)   Parameters:   x:  The number whose factorial has to be computed.  Return value:  Returns the factorial of desired number.  Exceptions:  Raises Value error if number is  negative or non-integral.

 # Python code to demonstrate math.factorial () import math   print ( "The factorial of 23 is:" , end = " ") print (math.factorial ( 23 ))

Output:

The factorial of 23 is: 25852016738884976640000

Exceptions in mathematics. Factorial ()

• If you give a negative number:

 # Python code to demonstrate math .factorial () # Exceptions (negative number)   import math   print ( "The factorial of -5 is: " , end = " ")   # throws an exception print (math.factorial ( - 5 ))

Output:

The factorial of -5 is:

Execution error:

Traceback (most recent call last): File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in print (math.factorial (-5)) ValueError : factorial () not defined for negative values ​​
• If the given number is not an integral value:

 # Python code to demonstrate math.factorial () # Exceptions (non-integers)   import math   print ( "The factorial of 5.6 is:" , end = "")   # throws an exception print (math.factorial ( 5.6 ))

Output:

The factorial of 5.6 is:

Runtime error:

Traceback (most recent call last): File "/home/3987966b8ca9cbde2904ad47dfdec124.py" , line 9, in print (math.factorial (5.6)) ValueError: factorial () only accepts integral values ​​

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.