程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Several methods of accumulating 1-100 in Python

編輯:Python

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)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved