在Python中,阶乘通常用 `n!` 表示,其中 `n` 是要计算阶乘的整数。阶乘 `n!` 是从 `1` 到 `n` 所有整数的乘积。例如,`5!` 表示 `5 * 4 * 3 * 2 * 1`,其结果是 `120`。
递归方法
def factorial_recursive(n):if n == 0:return 1else:return n * factorial_recursive(n - 1)
循环方法(使用 `for` 循环):
def factorial_iterative(n):result = 1for i in range(1, n + 1):result *= ireturn result
使用 `reduce()` 函数(从 `functools` 模块调用 `reduce()` 函数):

from functools import reducedef factorial_reduce(n):return reduce(lambda x, y: x * y, range(1, n + 1))
使用 `math.factorial()` 函数(Python 的内置 `math` 模块提供了一个 `factorial` 函数):
import mathdef factorial_math(n):return math.factorial(n)
选择哪种方法取决于你的具体需求和个人偏好
