[Python] break、continue、pass、return及exit的用法與區別

  • break 結束循環語句
  • continue 跳出本次循環,繼續下一個循環
  • pass 不做任何事情,站位而已
  • return 退出整個函數(def)
  • exit 結束整個程序(進程)

Table of Contents

<span class="ez-toc-title-toggle"><a href="#" class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" aria-label="顯示/隱藏內容目錄"><span class="ez-toc-js-icon-con"><span class=""><span class="eztoc-hide" style="display:none;">Toggle</span><span class="ez-toc-icon-toggle-span"><svg style="fill: #999;color:#999" xmlns="http://www.w3.org/2000/svg" class="list-377408" width="20px" height="20px" viewBox="0 0 24 24" fill="none"><path d="M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z" fill="currentColor"></path></svg><svg style="fill: #999;color:#999" class="arrow-unsorted-368013" xmlns="http://www.w3.org/2000/svg" width="10px" height="10px" viewBox="0 0 24 24" version="1.2" baseProfile="tiny"><path d="M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z"/></svg></span></span></span></a></span>

break

用來終止循環語句,即使循環條件沒有False或者序列還沒被完全遞歸完,也會停止執行循環語句。

break語句用在while和for循環中。

def config():
    for num in '12345':
        if num == '3':
            break
        print('當前數字:', num)
    print('=' * 10)

config()

結果如下:

當前數字: 1
當前數字: 2
==========

continue

continue 語句跳出本次循環,然後繼續進行下一輪循環。

def config():
    for num in '12345':
        if num == '3':
            continue
        print('當前數字:', num)
    print('=' * 10)

config()

輸出結果:當for迴圈到3時,被跳過了。

當前數字: 1
當前數字: 2
當前數字: 4
當前數字: 5
==========

pass

空語句,pass 不做任何事情,一般用做佔位語句,是為了保持程序結構的完整性。

def config():
    for num in '12345':
        if num == '3':
            pass
        print('當前數字:', num)
    print('=' * 10)

config()

結果如下:

當前數字: 1
當前數字: 2
當前數字: 3
當前數字: 4
當前數字: 5
==========

補充:

為什麼要站位?

事實上站位就是要先預留位置,回頭再補上具體的代碼實現。
很多時候我們在開發的時候,會把已知的判斷條件或函式寫好,然後在對應的塊中寫上pass,後續再慢慢完善這些站位的部分。

return

return 語句就是將結果返回到調用的地方,並把控制權也一起返回。

def config():
    for num in '12345':
        if num == '3':
            return f'for迴圈在 {num} 時回傳了'
        print('當前數字:', num)
    print('=' * 10)

print(config())
print('上方function已返回')

結果如下:

當前數字: 1
當前數字: 2
for迴圈在 3 時回傳了
上方function已返回

exit

用來結束整個程序(進程)。

def config():
    for num in '12345':
        if num == '3':
            exit()
        print('當前數字:', num)
    print('=' * 10)

config()
print('*' * 10)  #程式已結束所以不會印出

顯示如下:

當前數字: 1
當前數字: 2