课后练习:求1-100的所有数的和
作者:互联网
(1)while循环
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 n = 1 4 sum = 0 5 while n < 101: 6 print(n) 7 sum = sum + n 8 n = n + 1 9 print(sum)
(2)for循环
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 sum = 0 4 for a in range(1,101,1): 5 sum = sum + a 6 print(sum)
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 sum = 0 4 for a in range(1,101,1): 5 sum = sum + a 6 print(a) 7 print(sum)
执行结果:
12
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
5050 Process finished with exit code 0
标签:#-,sum,所有,coding,usr,env,print,课后练习,100 来源: https://www.cnblogs.com/xhdy/p/14268627.html