Maison >développement back-end >Tutoriel Python >python基础-循环
for循环:
a = [11,22,33,44]
for i in a:
print (i)
结果:
11
22
33
44
while循环:
i=0
while i < 3: #i<3为循环条件,当条件为真时,执行后面的循环体;条件为假时不执行
print (i)
i += 1
结果:
0
1
2
break和Continue:
i= 0
while i < 10:
print ("i->:",i)
if i == 5:
break #当i==5时,退出所有循环
i += 1
结果:
i->: 0
i->: 1
i->: 2
i->: 3
i->: 4
i->: 5
x=0
while x < 9:
for x in range(0,10):
if x ==6:
continue #当x==6时,跳出当前循环,继续下一次循环
print("x->:", x)
结果:
x->: 0
x->: 1
x->: 2
x->: 3
x->: 4
x->: 5
x->: 7 #缺少x->: 6
x->: 8
x->: 9
其他:
enumrate:
a = ["aa","bb","cc","dd"]
for i in enumerate(a,5): #默认编号从0开始,可以手动变更
print (i)
结果:
(5, 'aa')
(6, 'bb')
(7, 'cc')
(8, 'dd')
range:
1、
for n in range(1, 10):
print (n)
结果:
1
2
3
4
5
6
7
8
9
2、
for x in range(0,20,4):
print (x)
结果:
0
4
8
12
16
#以4作为step,依次打印