python循环结构
1.1 使用while
Python 中没有 do…while 循环
while … else 在条件语句为 false 时执行 else 的语句块:
list = [1,2,3,4,5]
i = 0
while i < len(list):
print(list[i])
i += 1
1
2
3
4
5
# while可以使用else语句
list = [1,2,3,4,5]
i = 0
while i < len(list):
print(list[i])
i += 1
else :
print('**** 程序执行结束 *****')
1
2
3
4
5
**** 程序执行结束 *****
1.2 使用for
for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
一般结构如下
for <variable> in <sequence>:
<statements>
else:
<statements>
# 遍历数字, 可以使用range方法
for i in range(6):
print(i)
# 第二个参数不可达,第三个参数为步长不指定时,默认为1
for i in range(2,6,2):
print(i)
0
1
2
3
4
5
2
4