當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python math.factorial()用法及代碼示例


在Python中,數學模塊包含許多數學運算,可以使用該模塊輕鬆執行。math.factorial()函數返回所需數字的階乘。

用法: math.factorial(x)

參數:
x: This is a numeric expression.

返回:  factorial of desired number.

代碼1:

# Python code to demonstrate the working of factorial() 
    
# importing "math" for mathematical operations  
import math  
    
x = 5
    
# returning the factorial 
print ("The factorial of 5 is:", end ="")  
print (math.factorial(x))
輸出:
The factorial of 5 is:120

代碼2:

# Python code to demonstrate the working of factorial() 
  
# importing "math" for mathematical operations  
import math  
  
x = 5
y = 15
z = 8
  
# returning the factorial 
print ("The factorial of 5 is:", math.factorial(x)) 
print ("The factorial of 15 is:", math.factorial(y)) 
print ("The factorial of 8 is:", math.factorial(z))

輸出:

The factorial of 5 is: 120
The factorial of 15 is: 1307674368000
The factorial of 8 is: 40320


代碼3:如果x不是整數,則引發ValueError

# Python code to demonstrate the working of factorial() 
    
# importing "math" for mathematical operations  
import math  
    
# when x is not integer 
print ("math.factorial(13.7):", math.factorial(13.7))

輸出:

ValueError:factorial() only accepts integral values


相關用法


注:本文由純淨天空篩選整理自Shivam_k大神的英文原創作品 Python | math.factorial() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。