Home > Article > Backend Development > 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!