阶乘python
时间: 2023-06-22 07:24:33 浏览: 42
计算阶乘可以使用递归或循环,以下是两种写法:
使用递归:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
```
使用循环:
```python
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
```
两种写法的效果相同,输入一个正整数n,返回n的阶乘。
相关问题
阶乘python代码
以下是 Python 中计算阶乘的代码:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
```
使用方法:
```python
n = 5
result = factorial(n)
print(result)
```
输出结果为:120
n的阶乘Python
以下是几种Python实现n的阶乘的方法:
1.使用for循环计算n的阶乘
```python
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
print(factorial(5)) # 输出:120
```
2.使用递归计算n的阶乘
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # 输出:120
```
3.使用reduce函数计算n的阶乘
```python
from functools import reduce
def factorial(n):
return reduce(lambda x, y: x*y, range(1, n+1))
print(factorial(5)) # 输出:120
```
4.使用math库中的阶乘函数计算n的阶乘
```python
import math
print(math.factorial(5)) # 输出:120
```