Home  >  Article  >  Backend Development  >  How to use for loop to sum in python

How to use for loop to sum in python

尚
Original
2019-07-06 16:18:1715760browse

How to use for loop to sum in python

You can use a for loop to implement cumulative summation in Python

for loop syntax:

 for 变量 in range(x):
      循环需要执行的代码

The following implements the summation from 1 to n:

def main():
  sum = 0    # 定义变量做累加器
  n = int(input('n='))   #从键盘上输入累加的范围
  for x in range(n):   
    sum += (x + 1)
  print(sum)
 
if __name__ == '__main__':
  main()

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to use for loop to sum in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn