当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python factorial()用法及代码示例


没有多少人知道,但是python提供了直接函数,可以计算数字的阶乘而不用编写用于计算阶乘的整个代码。

Naive method to compute factorial

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

输出:


The factorial of 23 is:25852016738884976640000

Using math.factorial()

该方法在python的“math”模块中定义。由于它具有C类型的内部实现,因此速度很快。

math.factorial(x)
参数:
x: The number whose factorial has to be computed.
返回值:
Returns the factorial of desired number.
异常:
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))

输出:

The factorial of 23 is:25852016738884976640000

Exceptions in math.factorial()

  • 如果给定数字为负数:
    # Python code to demonstrate math.factorial() 
    # Exceptions ( negative number ) 
      
    import math 
      
    print ("The factorial of -5 is:",end="") 
      
    # raises exception 
    print (math.factorial(-5))

    输出:

    The factorial of -5 is:
    

    运行时错误:

    Traceback (most recent call last):
      File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in 
        print (math.factorial(-5))
    ValueError:factorial() not defined for negative values
    
  • 如果给定数字为非整数值:
    # Python code to demonstrate math.factorial() 
    # Exceptions ( Non-Integral number ) 
      
    import math 
      
    print ("The factorial of 5.6 is:",end="") 
      
    # raises exception 
    print (math.factorial(5.6))

    输出:

    The factorial of 5.6 is:
    

    运行时错误:

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


相关用法


注:本文由纯净天空筛选整理自 factorial() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。