1. use for loop
one = 0
for i in range(1,101):
one = one+i
print(one)
2. use sum() function
two = sum(range(101))
print(two)
3. use while loop
three = 0
i = 1
while i < 101:
three = three+i
i+=1
print(three)
4. use reduce function ,reduce() Is to accept a function and an iteratable sequence , In each iteration , The output of both the current element and the previous element is passed to the function , Function returns a value at the end .
lambda The function takes two arguments , And returns the sum of the two elements .
from functools import reduce
four = reduce(lambda a,b:a+b,range(1,101))
print(four)
I have a question right away ?
reduce Just keep adding up the two adjacent elements , Why does it return a number in the end , in fact reduce The working process is like this : During the iteration sequence , First turn on the First two elements ( Only two. ) Pass to function , After function processing , And then put The result and the third element Pass it as two parameters to the function parameter , The result of function processing is the same as the fourth element Pass it as two parameters to the function parameter , By analogy .
Or it can be understood in this way : After the operation on the first two elements, a value is returned and the remaining elements continue to form a list , Insert list header , Then take the first two elements from the list , cycle , Until the list is empty , Return the last value ( Of course, the actual situation should not be like this )
for example 1-5 The addition of :((((1+2)+3)+4)+5)