在Python中,阶乘符号 `!` 表示连续整数的乘积,即 `n! = 1 * 2 * 3 * ... * n`。
要计算阶乘,你可以使用以下方法:
1. 使用内置函数 `math.factorial(n)`:
```python
import math
result = math.factorial(5)
print(result) 输出:120
2. 使用递归函数:
```python
def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n-1)
print(factorial_recursive(5)) 输出:120
3. 使用 `for` 循环:
```python
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
print(factorial_iterative(5)) 输出:120
4. 使用 `reduce()` 函数:
```python
from functools import reduce
def factorial_reduce(n):
return reduce(lambda x, y: x * y, range(1, n+1))
print(factorial_reduce(5)) 输出:120
以上是计算阶乘的几种方法。你可以根据具体需求选择合适的方法