在Python中,表示阶乘可以通过以下几种方法:
1. 使用内置函数 `math.factorial(n)`
import mathresult = math.factorial(5)print(result) 输出:120
2. 使用for循环手工计算
def factorial(n):result = 1for i in range(1, n + 1):result *= ireturn resultprint(factorial(5)) 输出:120
3. 使用递归函数

def factorial_recursive(n):if n < 0:return "错误:负数没有阶乘"if n == 0 or n == 1:return 1return n * factorial_recursive(n - 1)print(factorial_recursive(5)) 输出:120
4. 使用列表推导和乘法运算符
n = 5factorial = 1for i in range(1, n + 1):factorial *= iprint(factorial) 输出:120
5. 使用 `reduce()` 函数(Python 2)
from functools import reduceresult = reduce(lambda x, y: x * y, range(1, n + 1))print(result) 输出:120
以上是Python中表示阶乘的几种方法。您可以根据需要选择合适的方法进行计算
