Python學習筆記之Break和Continue用法分析
本文實例講述了Python學習筆記之Break和Continue用法。分享給大家供大家參考,具體如下:
Python 中的Break 和 Continue
- break:控制何時循環(huán)應該結(jié)束
- continue: 跳過循環(huán)的一次迭代
Break 和 Continue[示例練習]
用 break 語句寫一個循環(huán),用于創(chuàng)建剛好長 140 個字符的字符串 news_ticker。你應該通過添加 headlines 列表中的新聞標題創(chuàng)建新聞提醒,在每個新聞標題之間插入空格。如果有必要的話,從中間截斷最后一個新聞標題,使 news_ticker 剛好長 140 個字符
headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" for item in headlines: news_ticker += item + " " if len(news_ticker) >= 140: news_ticker = news_ticker[:140] break print(news_ticker) # Local Bear Eaten by Man Legislature Announces New Laws Peasant Discovers Violence Inherent in System Cat Rescues Fireman Stuck in Tree Brave print(len(news_ticker)) # 140
運行結(jié)果:
Local Bear Eaten by Man Legislature Announces New Laws Peasant Discovers Violence Inherent in System Cat Rescues Fireman Stuck in Tree Brave
140
break與continue的區(qū)別:
1、break:終止,跳出,結(jié)束循環(huán)(可以作用在任何地方)。常與switch分支結(jié)構(gòu)合用。
2、continue:結(jié)束本次的循環(huán),進入下一次的循環(huán)(只能運用到循環(huán)結(jié)構(gòu)中)。
關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python接口自動化測試數(shù)據(jù)和代碼分離解析
代碼的可維護性除了代碼冗余之外還有就是數(shù)據(jù)盡量不要和代碼摻雜在一起,因為閱讀起來會非常的凌亂;數(shù)據(jù)分離能更好的增加代碼可讀性和可維護性,也能更好的二次修改使用2021-09-09詳解Python中常用的激活函數(shù)(Sigmoid、Tanh、ReLU等)
激活函數(shù) (Activation functions) 對于人工神經(jīng)網(wǎng)絡(luò)模型去學習、理解非常復雜和非線性的函數(shù)來說具有十分重要的作用,這篇文章主要介紹了Python中常用的激活函數(shù)(Sigmoid、Tanh、ReLU等),需要的朋友可以參考下2023-04-04