Python math.factorial() 方法



Python 的math.factorial() 方法用於計算非負整數的階乘。非負整數 n 的階乘,表示為 n!,是從 1 到 n 的所有正整數的乘積。在數學上,n 的階乘計算如下:

n! = n × (n-1) × (n-2) ×...× 2 × 1

換句話說,n 的階乘是小於或等於 n 的所有正整數的乘積。按照慣例,0! 定義為 1。

例如:

  • 5! = 5 × 4 × 3 × 2 × 1
  • 4! = 4 × 3 × 2 × 1
  • 0! = 1

語法

以下是 Python math.factorial() 方法的基本語法:

math.factorial(n)

引數

此方法接受一個非負整數作為引數,用於計算其階乘。

返回值

此方法返回一個整數,表示給定非負整數 n 的階乘。

示例 1

在下面的示例中,我們使用math.factorial() 方法計算 5 的階乘:

import math
result = math.factorial(5)
print("The result obtained is:",result) 

輸出

獲得的輸出如下:

The result obtained is: 120

示例 2

在這裡,我們使用math.factorial() 方法計算 0 的階乘:

import math
result = math.factorial(0)
print("The result obtained is:",result) 

輸出

以下是上述程式碼的輸出:

The result obtained is: 1

示例 3

在此示例中,我們使用變數“n”儲存值“7”。然後我們計算 n 的階乘,表示為 7!:

import math
n = 7
result = math.factorial(n)
print("The result obtained is:",result) 

輸出

我們得到如下所示的輸出:

The result obtained is: 5040

示例 4

如果我們向factorial() 方法傳遞一個非負整數,它會引發 ValueError,因為它僅接受整數作為引數:

import math
result = math.factorial(5.5)
print("The result obtained is:",result) 

輸出

生成的輸出如下所示:

Traceback (most recent call last):
  File "/tmp/main.py", line 2, in <module>
    import user_code
  File "/tmp/user_code.py", line 2, in <module>
    result = math.factorial(5.5)
             ^^^^^^^^^^^^^^^^^^^
TypeError: 'float' object cannot be interpreted as an integer
python_maths.htm
廣告