for循环的最基本用法
for i in range(10): # 这里指循环10次 print("loop:",i)
运行结果,如图
将上节课的while循环,修改为for循环,如
count = 0 age_of_oldboy = 56 for i in range(3): guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it!") break elif guess_age > age_of_oldboy: print("think smaller....") else: print("think bigger...") else: print("you have tried too many times....")
运行结果,如图:
如果在for循环中想实现隔2个打印一个,比如要打印0 2 4 6 8 ,如何实现呢
for i in range(0,10,2) # 注意这里的2指的就是步长,代表的是中间隔2个数 print("loop:",i)
运行结果,如图
升级while循环,如果输入3次,循环是否继续
count = 0 age_of_oldboy = 56 while count < 3: guess_age = int(input("guess_age:")) if guess_age == age_of_oldboy: print("yes,you got it!") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger...") count = count+1 if count == 3: countine_confirm = input("do you want to keep guessing...") if countine_confirm != "n": count = 0
for循环与continue的结合使用
continue是跳出本次循环,进入下个循环,break是结束当前循环
for i in range(10): print("---", i) if i > 5: continue # continue是跳出本次循环,进入下个循环 print("zwt")
运行结果,如图
for循环与break的结合使用
for i in range(10): print("---", i) for j in range(10): print(j) if j > 5: break # 注意此处的break是结束本次循环,也就是只结束内层循环,外层循环不受影响
运行结果,如图