continue: 返回到循环开头,并根据条件测试结果决定是否继续执行循环。
例:
n=0 while n<10: n+=1 if n%2==0: continue #返回到循环开头 print(n)
运行结果:
====================== RESTART: D:/python学习/continue.py ====================== 1 3 5 7 9 >>>
break:用于控制程序的流程,可使用它来控制哪些代码行将执行,从而让程序按你的要求执行。(在循环中都可使用break语句,立即退出不再执行余下的代码)
例:
prompt='\nPlease enter the name of a city you have visited:' prompt+='\n(Enter "quit" when you are finished.' while True: city=input(prompt) if city=="quit": break else: print("I'd love to go to "+city.title()+"!") #title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写
运行结果:
>>>
======================= RESTART: D:/python学习/break.py =======================
Please enter the name of a city you have visited:
(Enter "quit" when you are finished.beigjing
I'd love to go to Beigjing!
Please enter the name of a city you have visited:
(Enter "quit" when you are finished.广州
I'd love to go to 广州!
Please enter the name of a city you have visited:
(Enter "quit" when you are finished.quit
>>>