Python中可以使用for循环实现累加求和
for循环语法:
1
2
3
|
for 变量 in range (x): 循环需要执行的代码 |
如下实现1到n求和:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def main(): sum = 0 # 定义变量做累加器 n = int ( input ( 'n=' )) #从键盘上输入累加的范围 for x in range (n): sum + = (x + 1 ) print ( sum ) if __name__ = = '__main__' : main() |
用for循环实现1~n求和的方法
1
2
3
4
5
6
7
8
9
|
def main(): sum = 0 n = int ( input ( 'n=' )) for x in range (n): sum + = (x + 1 ) print ( sum ) if __name__ = = '__main__' : main() |
原文链接:http://www.php.cn/python-tutorials-425079.html