以下给出五种解题角度(for循环、while循环、列表推导式、reduce函数、递归函数)
①for循环
sum = 0
for i in range(101):
sum += i
print(sum)
②while循环
sum = 0
i=1
while i <= 100:
sum += 1
i += 1
print(sum)
③列表推导式(直接利用sum函数)
sum = sum([i for i in range(101)])
print(sum)
④reduce函数
from functools import reduce
sum = reduce(lambda x,y: x + y,range(101))
print(sum)
⑤递归函数
def sum_recursive(n):
if n == 0:
return 0
return n + sum_resursive(n-1)
sum = sum_recursive(100)
print(sum)