沒有多少人知道,但是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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。