内容框图
4.1 了解循环
# 认识循环
for x in range(10):
print("hello world") # 循环操作:重复执行的业务
4.2 for循环
# for循环
# for 变量名 in 序列:
# 循环语句
for s in range(0, 10,2):
print("第", s, "次打印hello world")
for x in ["a", "b", "c"]:
print(x)
4.3 for循环遍历容器
# for循环遍历容器
names = ["张三","李四","王五","赵六"]
# 直接遍历
for name in names:
if name=="王五":
print("有这个人 王五")
# 构造索引
for i in range(0, len(names)):
print(names[i])
scores = (67,78,56,89,76,79,98,45,65,76)
for i in range(0, len(scores)):
print(scores[i])
total = 0
for score in scores:
total = total + score
print(total/len(scores))
# 循环遍历字典,只获取键
dicta = {"name":"zhangsan","age":18,"hobby":"play ball"}
for x in dicta:
print(x,dicta[x])
seta = {1,23,232,43,345,46,56}
for x in seta:
print(x)
4.4 while循环
i = 1
while i<=10:
print("第", i, "次打印:hello world!")
i = i + 1
# for适合循环次数确定的业务 可以直接遍历容器
# while适合已知循环执行条件的业务
4.5 嵌套循环
# 嵌套循环
for year in range(1,11):
print("第",year,"年到了!还款1.2万")
for month in range(1,13):
print("第", month, "月,还款1000元!")
# 遍历多维容器
lista = [1,213,13,232,3,43,3,3]
listb = [21,22,23,24,25,26,27]
listc = [111,222,333,444,555]
listx = [lista, listb,listc]
for x in listx:
for s in x:
print(s)
4.6 break和contine
# break:结束整个循环操作
# continue:结束本次循环,继续下次循环
for year in range(1,11):
if year==5:
print("疫情原因,今年不用还款了!")
if year==8:
print("第8年,提前还清,以后都不用还了!")
print("第",year,"年到了!还款1.2万!")