循环语句
- python有两种循环,一种是for循环;
names = ['Michael','Bob','Tracy']
for name in names:
print (name)
Michael
Bob
Tracy
- for x in ... 把每一个元素循环带入给x,然后执行缩进快的语句;
range(5)
range(0, 5)
sum = 0
for x in [1,2,3,4,5,6,7,8,9]:
sum = x + sum
print (sum)
45
如果计算1-100之间的和,需要由range()函数,可以生成一个整数序列,在通过list()函数可以转换成list;
list(range(5))
[0, 1, 2, 3, 4]
for x in range(5):
print (x)
0
1
2
3
4
- 计算1..100相加
sum = 0
for x in range(101):
sum += x
print (sum)
5050
sum = 0
for x in range(101):
sum = x + sum
print (sum)
5050
- 另一种循环,while循环,计算奇数之和
sum = 0
n = 99
while n > 0:
sum += n
n = n - 2
print(sum)
2500
- 计算1..100的和
sum = 0
n = 100
while n > 0:
sum = n + sum
n = n - 1
print (sum)
5050
- break,退出
n = 1
while n <= 100:
print(n)
n += 1
print('END')
1
2
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
END
n = 1
while n <= 100:
if n > 10:
break
print (n)
n = n + 1
print ('END')
1
2
3
4
5
6
7
8
9
10
END
- continue ,再循环过程中跳出当前循环,直接开始下一个循环
n = 0
while n < 10:
n = n + 1
if n % 2 == 0:
continue
print (n)
1
3
5
7
9