1 分鐘搞懂Python 迴圈控制:break、continue、pass - Medium
文章推薦指數: 80 %
continue. 當偵測到字母 t 時,會跳過本次迴圈剩下的程式碼 print(string) ...
GetstartedOpeninappChiaYinChenSigninGetstarted112FollowersAboutGetstartedOpeninapp1分鐘搞懂Python迴圈控制:break、continue、passChiaYinChenAug6,2018·6minreadPhotobyTineIvaničonUnsplash在使用迴圈時,你是否遇過需要在特定情況下,提早結束本次迴圈的進行或是強制結束迴圈呢?這篇文章將會介紹如何使用Python中的break、continue、pass語句來改變正常迴圈的程序。
先來簡單敘述一下Python中break、continue、pass的區別:break:強制跳出❮整個❯迴圈continue:強制跳出❮本次❯迴圈,繼續進入下一圈pass:不做任何事情,所有的程式都將繼續break當偵測到字母t時,就會強制結束迴圈:count=0forstringin'content':count+=1ifstring=='t':breakprint(string)print('\n迴圈結束')print('迴圈執行了%d次'%count)continue當偵測到字母t時,會跳過本次迴圈剩下的程式碼print(string),但不會結束迴圈,仍然會進入下一圈繼續執行:count=0forstringin'content':count+=1ifstring=='t':continueprint(string)print('\n迴圈結束')print('迴圈執行了%d次'%count)pass當偵測到字母t時,會忽略該條件,繼續像正常迴圈一樣運行程序:count=0forstringin'content':count+=1ifstring=='t':passprint(string)print('\n迴圈結束')print('迴圈執行了%d次'%count)在迴圈中使用pass語句,執行程式後,你會發現什麼事也沒做,完全不起任何作用,只是一個空運算而已,那問題就來了:如果什麼事都不做,就不用寫拉,那pass語句是要做什麼的?……✍︎其實有時候會有非寫不可的情況!!pass就像是Todo的概念,在寫程式的時候,有時候想的比實際寫出來的速度快,例如定義一個函數,但還沒有實作出來,空著內容不寫又會產生語法錯誤🤦♂️,這時就會使用pass來替代,當作是個指標,提醒自己之後要來完成。
defmyfunction():pass#提醒自己之後要來完成應用場景範例情境1:過濾取出整數{…,-2,-1,0,1,2,…},過濾掉非整數的值。
#定義函數deffilter_out_non_int(elements):result=[]forelementinelements:iftype(element)!=int:continueresult.append(element)returnresult#呼叫函數filter_out_non_int([0,'one',2,3,'four',5,'six','seven',8,9,10])📝Note:利用continue告訴迴圈當element的type為非整數時,要跳出本次迴圈,繼續進入下一圈執行。
情境2:比對檢查email是否為公司官方信箱,如出現hello、contact、sales、support、business、info等關鍵字。
importre#定義函數defdetect_email(email):email_out=['hello','contact','sales','support','business','info']fore_outinemail_out:pattern=re.compile('.*'+e_out+'.*')r=re.match(pattern,email.lower())ifrisnotNone:print('{}中包含{}關鍵字,因此判斷為官方信箱'.format(email,e_out))breakelse:print('{}為個人信箱'.format(email))#呼叫函數detect_email('[email protected]')detect_email('[email protected]')📝Note:利用break告訴迴圈當email字串中包含email_out列表(List)中的關鍵字時,要強制結束迴圈。
情境3:限制數量限制列表(List)儲存空間的長度。
#定義函數defnumber_sum_limit(nums,limit):result=[]s=0fornuminnums:iflen(result)==limit:breakiftype(num)==str:continueresult.append(num)s+=numreturnresult,'sum={}'.format(s)#呼叫函數number_sum_limit(nums=[7.5,8,'aa',4.75,'bb',2,8,5,6],limit=5)📝Note:利用break告訴迴圈當result列表(List)中的元素數量超過5個時,必須停止繼續加總剩下的值,強制結束迴圈。
利用continue告訴迴圈當元素的type為字符串時,要跳出本次迴圈,繼續進入下一圈執行。
搞懂了break、continue、pass語句之後,相信可以讓大家更靈活的運用迴圈✌️ChiaYinChenDataEngineerFollow5131513 5131PythonLoopMorefromChiaYinChenFollowDataEngineer
延伸文章資訊
- 1continue (【動詞】繼續, 持續)意思、用法及發音| Engoo Words
"continue" 例句. They continued their conversation after lunch. 他們在午餐後繼續談話。 Let's take a short brea...
- 2Definition of continue - Merriam-Webster
Definition of continue · 1 : to maintain without interruption a condition, course, or action The ...
- 3continue - Yahoo奇摩字典搜尋結果
continue · vi. 持續; 持續下去; 持續不斷;繼續; 繼續進行 · vt. 繼續;再開始; (中斷後)繼續 ...
- 4動詞continue 後面可以接to-V,也可以接V-ing
continue 後面可以加不定詞to-V, 也可加動名詞V-ing, 例句如下: He continued to play basketball. 他先前打過了籃球,後再繼續. He cont...
- 5continue中文(繁體)翻譯:劍橋詞典
continue的例句. continue. The views down the crossings of the field are continued in the agricultura...