python之循环控制语句
1、for循环
格式1:i=i+1
for i in range(5): print(i)
格式2:j=j+2
for j in range(1,15,2): print("j=:",j)
格式3:遍历字符串
str="happy" for k in str: print(k)
格式4:遍历数组1
a=["aa","bb","cc","dd"] for p in a: print(p,end="\t")
格式5:遍历数组2
b=["aa","bb","cc","dd"] for t in range(len(b)): print(t,b[t],end="\t")
end="\t"表示间隔符为\t
2、while循环
格式:
i=0 while i<5: print("第%d次执行循环"%(i+1)) print("i=",i) i=i+1
while与else
count=1 while count<5: print(count,"小于5") count +=1 else: print(count, "大于或等于5")
若无else,while中不会输出5这个值
break continue pass
1)break 打破跳出for或while循环体
2)continue跳过当前循环进入下一循环
3)pass是空语句,一般用作占位语句,不做任何事情
3、练习题:九九乘法表
1)for循环
i=1 j=1 for i in range(1,10): for j in range(1,i+1): if(i!=j): print("%d*%d=%d"%(i,j,i*j),end="\t") else: print("%d*%d=%d" % (j, i, i * j), end="\t") print("\n")
2)while循环:
i = 1 j = 1 while i < 10: while j < i + 1: if i != j: print("%d*%d=%d" % (i, j, i * j), end="\t") else: print("%d*%d=%d" % (i, j, i * j), end="\t") print("\n") j += 1 i += 1 j=1