1,pass: 过,(占位)
eg:
if 10 == 10:
print(123)
while True:
pass
2,break: 终止当前循环
#终止的是当前循环
eg:
i = 1
while i <= 3:
j = 1
while j<=3:
if j == 2:
break
print(i,j)
j+=1
i+=1
3,continue: 跳过当前循环,从下一循环开始
eg
# 打印1~10 跳过5
i = 1
while i<=10:
if i == 5:
# 需手动自增加1. 当执行continue时,后面的代码不执行,跳到while循环的条件判断处,会造成死循环
i+=1
continue
print(i)
i+=1
```
eg;
打印1~ 100 所有不含有4的数字
//可以取到一个数的高位
% 可以取到一个数的低位
46 // 10 = 4
46 % 10 = 6
"""
# 方法一
i = 1
while i<=100:
if i // 10 == 4 or i % 10 == 4:
i+=1
continue
print(i)
i+=1
# 方法二
print("<=====>")
i = 1
while i <= 100:
strvar = str(i)
if "4" in strvar:
i+=1
continue
print(i)
i+=1
4,forx
(1)循环:遍历,循环,迭代
eg;
lst = ["刘鑫","刘子豪","刘子涛","晏国彰"]
i = 0
while i<len(lst):
# 代码的逻辑
print(lst[i])
i+=1
(2)主要用于遍历数据而提出,while 在遍历数据时,有局限性
for 变量 in 可迭代对象:
可迭代对象(容器类型数据,range对象,迭代器)
eg:
遍历字符串
container = "雷霆嘎巴,ZBC,无情哈拉少"
遍历列表
container = ["刘鑫","刘子豪","刘子涛","晏国彰"]
遍历元组
container = (1,2,3,45)
遍历集合
container = {"白星","高峰峰","孙志和","刘鹏","牧树人"}
#遍历字典 (遍历字典时,只遍历键)
container = {"ww":"伟大的人,风流倜傥","msr":"树人,伟大的人","mh":"猥琐的老男人"}
for i in container:
print(i)
eg:
遍历不等长的二级容器
container = [["刘聪","毛洪磊","余锐","张家豪"],("崔文君","张捷")]
for i in container:
# print(i)
for j in i:
print(j)```
eg:变量的解包
a,b = 1,2
a,b = [3,4]
a,b = {"a":5,"b":6}
print(a,b)
遍历等长的二级容器
container = [("王健林","王思聪","王美丽") , ("马云","马化腾","马生平") , ("王宝强","马蓉","宋小宝") ]
for a,b,c in container:
print(a,b,c)
# a,b,c = ("王健林","王思聪","王美丽")
# a,b,c = ("马云","马化腾","马生平")
# a,b,c = ("王宝强","马蓉","宋小宝")
range对象
"""
range(开始值,结束值,步长)
结束值本身取不到,取到结束值之前的那个数
"""
# 只有一个值 0~9
for i in range(10):
print(i)
# 只有两个值
for i in range(3,11):
print(i)
# 只有三个值
for i in range(1,10,3):
print(i) # 1,4,7
#1 (1+3)=>4 (4+3)=>7 (7+3)=>10取不到
# 倒序打印10 ~ 1
for i in range(10,0,-1):
print(i)
# 10 9 8 7 6 .... 1
总结:
while : 较为复杂的逻辑
for : 数据的遍历
while 和 for 部分代码可以互相转换
区别写法1
i = 1
while i<=10:
if i == 5:
i+=1
continue
print(i)
i+=1
for i in range(1,11):
if i == 5:
continue
print(i)
区别写法2
i = 1
while i <= 9:
j = 1
while j<=i:
print("%d*%d=%2d " % (i,j,i*j),end="")
j+=1
print()
i+=1
for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%2d " % (i,j,i*j),end="")
print()