一、while循环
①while
while 条件:
条件成立,重复执行代码
i = 0
while i < 3:
print(i)
i += 1
0
1
2
②while循环嵌套
while 条件1:
while 条件2:
条件1,条件2同时成立,执行dm
i = 0
while i < 2:
i += 1
j = 0
while j < 2:
j += 1
print(1)
1
1
1
1
③while...else...循环
while 条件:
条件成立,重复执行代码
else:
条件不成立,执行代码
如下题:
求100~200的所有素数
i = 100
while i <= 200:
j = 2
while j < i:
if i % j == 0:
break
j += 1
else:
print(i)
i += 1
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
④break和continue
break:终止所有循环,不再执行
continue:中止当前循环,执行下一次循环
二、for循环
①for
for 临时变量 in 序列:
重复执行代码
str1 = "abc"
for i in str1:
print(i)
a
b
c
②for循环嵌套
for 临时变量1 in 序列1:
for 临时变量2 in 序列2:
重复执行代码
for i in range(2)
for j in range(2)
print(1)
1
1
1
1
③for...else...
for 临时变量 in 序列:
重复执行代码
else:
循环正常结束,执行代码
如下题:
求100~200的所有素数
for i in range(100, 201):
for j in range(2, i):
if i % j == 0:
break
else:
print(i)
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
④break和continue
break:终止所有循环,不再执行
continue:中止当前循环,执行下一次循环