• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
QQ糖_尤尤
博客园    首页    新随笔    联系   管理    订阅  订阅
break和continue在while循环中

 

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
>>>

 

posted on 2021-01-14 15:40  QQ糖_尤尤  阅读(197)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3