输入正整数n,输出1+2+3+……+n-1+n的和
函数求和
n = int(input('请输入想求和的数字:'))
print(sum(range(1,n+1)))
高阶函数reduce
from functools import reduce
n = int(input('请输入想求和的数字:'))
print(reduce(lambda a,b:a+b,list(range(1,n+1))))
#普通求和
n = int(input('请输入想求和的数字:'))
sum = 0
for i in range(1,n+1):
sum = sum + i
print(sum)
#递归求和
a = int(input('请输入想求和的数字:'))
def fun(n):
if n == 1:
return n
n = n + fun(n-1)
return n
print(fun(a))