现在位置: 首页 > Python 3 教程 > 正文

Python math.factorial() 方法

Python math 模块 Python math 模块

Python math.factorial(x) 方法返回 x 的阶乘。

参数只能是正整数。

一个数字的阶乘是所有整数的乘积之和,例如,6 的阶乘是: 6 x 5 x 4 x 3 x 2 x 1 = 720

语法

math.factorial() 方法语法如下:

math.factorial(x)

参数说明:

  • x -- 必需,正整数。如果数字为负数或不是整数,则返回 ValueError。 如果值不是数字,则返回 TypeError。

返回值

返回一个正整数,表示正整数的阶乘。

实例

以下实例返回正整数的阶乘:

实例

# 导入 math 包
import math

# 输出正整数的阶乘
print(math.factorial(9))
print(math.factorial(6))
print(math.factorial(12))

输出结果:

362880
720
479001600

Python math 模块 Python math 模块