一.for循环
1.遍历 循环 迭代 => 把容器类型中的数据一个个获取一下
lst = [10,20,30,40] i = 0 while i < len(lst): print(lst[i]) i += 1
2.while 有个别数据类型中,无法遍历数据,for循环应用而生
1.1 for 循环
""" Iterable : 可迭代性数据(容器类型数据,range对象,迭代器) for 变量 in Iterable: code1 code2 """
1.2 遍历不等长的二级容器
container = [("特","白鸽","建康"),["菲菲","王"],{"赵沈"}]
for i in container:
# print(i)
for j in i :
print(j)
1.3遍历等长的二级容器
container = [("马保国","马户","马累"),["王健林","王思聪","王寅"],("马云","马化腾","马伊琍")]
for a,b,c in container:
print(a,b,c)
3 . range对象 流头舍尾
for i in range(1,10,3): # 1 4 7 print(i) for i in range(9,0,-1): print(i) # 2. range( start , end ) for i in range(3,7): # 3 4 5 6 print(i) # 3.range(end) 从0开始,留头舍尾 for i in range(3): print(i)
4.while 和 for循环的应用场景
"""
复杂逻辑使用: while
遍历数据使用: for
在大多数情况下,两个循环可以互相通用;
"""
二. 关键字
1. pass 过,用来做占位
"""
if 5 == 5:
pass
while True:
pass
"""
2. break 终止当前循环(只能应用在循环之中)
# 1 ~ 10 遇到5,终止循环
i = 1 while i <= 10 : print(i) if i == 5 : break i += 1 i = 1 while i <= 3: j = 1 while j <= 3: if j == 2: break print(i,j) # (1,1) (2,1) (3,1) j += 1
不能把break放在循环外层
i += 1
3.continue 跳过当前循环,从下一次循环开始 (只能应用在循环之中)
# 打印1 ~ 10 ,跳过5
# while i = 1 while i <= 10: if i == 5: # 在while循环中continue跳过时,又可能出现死循环,需要手动加1; i += 1 continue print(i) i += 1 # for for i in range(1,11): if i == 5: continue print(i)
# 打印 1~100所有不含有4的数字
# 方法一 i = 1 while i <= 100: # 个位是4 或者 十位是4 都不要 if i // 10 == 4 or i % 10 == 4: i += 1 continue print(i) i += 1 print("<------------------>") for i in range(1,101): # 个位是4 或者 十位是4 都不要 if i // 10 == 4 or i % 10 == 4: continue print(i) print("<------------------>") # 方法二 i = 1 while i <= 100: strvar = str(i) if "4" in strvar: i+=1 continue print(i) i += 1