最简单的循环10次
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#-*- coding: utf-8 -*- #Author = "zero" for i in range(10): print("loop:",i)
输出:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
loop: 0 loop: 1 loop: 2 loop: 3 loop: 4 loop: 5 loop: 6 loop: 7 loop: 8 loop: 9
需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(10): if i<5: continue #不往下走了,直接进入下一次loop print("loop:", i )
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(10): if i>5: break #不往下走了,直接跳出整个loop print("loop:", i )
需求三:还是上面的程序,但是每跳一个打印一个,打印完毕退出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(0,10,2): print("loop ",i)
加断点测试continue用法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(0,10): if i < 3: print("loop ",i) else: continue print("hehe......")
两个for循环
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(10): print("-------------",i) for j in range(10): print(j)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for i in range(10): print("-------------",i) for j in range(10): print(j) if j>5: break
总结:continue跳出本次循环,进入下一次循环,break结束当前当次整个循环。
用for代替刚刚的猜年龄程序:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
age_of_oldboy = 28 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 bigger!") else: print("think smaller......") else: print("you have tried too many times..funck off!!")
还是猜年龄程序,要求每猜错三次提示“还要不要继续玩?”
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
age_of_oldboy = 28 count = 0 while count < 3: guess_age = in(input("guess age:")) if guess_age == age_of_oldboy : print("yes, you got it.") break elif guess_age < age_of_oldboy: print("think bigger!") else: pirnt("think smaller......") count +=1 if count == 3 countine_confirm = input("do you want to keep guessing..?") if countine_confirm !="n": # 不等于“n”继续循环 count = 0