计算1!+2!+......+n!用Python
时间: 2023-11-24 13:52:32 浏览: 133
Python多进程multiprocessing.Pool类详解
5星 · 资源好评率100%
以下是两种Python计算1!+2!+...+n!的方法:
1. 使用for循环来计算
```python
n = int(input())
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += factorial
print(sum)
```
2. 使用递归函数调用阶乘方法求和(其中n的值在1~40之间)
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
n = int(input())
sum = 0
for i in range(1, n+1):
sum += factorial(i)
print(sum)
```
阅读全文