Python 迴圈 break 和 continue

Jinku Hu 2023年1月30日 2018年2月12日
  1. breakcontinue 語法
  2. Python break 語法
  3. Python continue 語句
Python 迴圈 break 和 continue

在本節中,我們將通過示例學習 Python 程式設計中的 breakcontinue 語句。

breakcontinue 語法

break 語句跳出了最內層的封閉 forwhile 迴圈,continue 語句跳過當前迭代並繼續執行 for or while 迴圈的下一次迭代。

Python break 語法

break 語句在迴圈中使用時,它將終止迴圈並且控制將被傳遞到迴圈體之外。如果 break 在巢狀迴圈中使用該語句,則內部迴圈將終止。

break 語句通常是基於條件(if 條件)來執行的,當條件為真時,break 執行並且迴圈(forwhile)終止。

break 示例

for i in "Python":
        if i == "h":
            break
        print(i)
print("Outside for loop")
P
y
t
Outside for loop

這裡 i 遍歷了"Python"字串序列,當 i 等於 h 時,控制進入 if 並執行 break 語句且終止迴圈。當 i 不等於 h 之前,if 條件不為真,所以 print 語句可以被執行,並且列印出了字串"Python"h 之前的字元。

Python continue 語句

continue 語句跳過當前迭代,控制返回到迴圈的開始。在這種情況下,迴圈不會終止,而是繼續下一次迭代。

continue 示例

for i in "Python":
        if i == "h":
            continue
        print(i)
print("Outside for loop")
P
y
t
o
n
Outside for loop

這裡當 i 等於 h 時,將跳過當前迭代並繼續下一次迭代,你可以在輸出中看到 h 並未列印,但它前後前後的字母都被列印出來了。

因此,breakh 之後不會列印任何內容,但 continue 語句卻並不會如此。

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - Python Loop