python实现1加到100

时间:2022-07-14 09:46:51
'''
python实现任意数到任意数相加,如:1加到100
'''

#第一种是for循环
# def sum(start, end):
# sum = 0
# for one in range(start, end+1):
# sum = one + sum
# one += 1
# return sum
#
# result = sum(1, 100)
# print(result)

#第二种是while循环
def sum2(start,end):
i = start
sum = 0
while i <= end:
sum += i
i += 1
return sum

result = sum2(-0.01,100.0009)
print(result)

#第三种,导入模块的内建函数reduce,只能整数?
# from functools import reduce
# def sum(x, y):
# return x + y
# result = reduce(sum, range(1,101))
# print(result)