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

How to use for loop to sum in python

Release: 2019-07-06 16:18:17
Original
15799 people have browsed it

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):
      循环需要执行的代码
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template