使用普通的for循环
def factorial(n):result = 1for i in range(1, n + 1):result *= ireturn resultprint(factorial(5)) 输出:120
使用`reduce()`函数
from functools import reducedef factorial(n):return reduce(lambda x, y: x * y, range(1, n + 1))print(factorial(5)) 输出:120
使用`math.factorial()`函数
import mathdef factorial(n):return math.factorial(n)print(factorial(5)) 输出:120
使用递归函数
def factorial(n):if n == 0:return 1else:return n * factorial(n - 1)print(factorial(5)) 输出:120
使用`numpy.math.factorial()`函数(需要安装`numpy`库):
import numpydef factorial(n):return numpy.math.factorial(n)print(factorial(5)) 输出:120
以上是计算阶乘的几种常见方法。你可以根据自己的需要选择合适的方法。

