Python while 迴圈:條件重複執行與 break 跳出

Python while 迴圈是一種「只要條件成立就持續執行」的重複語法,與 for 迴圈不同,它的迭代次數不需要事先確定,適合用在「等待某個狀態改變」或「直到滿足終止條件才停止」的場景。本文完整解析 while 的基本語法、break 強制跳出、continue 跳過本次、else 子句、無限迴圈的正確使用方式,以及如何避免最常見的無窮迴圈(Infinite Loop)陷阱。

Cinematic dark alchemy forge with a glowing circular whirlpool of amber fire spinning in a stone chamber, a mystical gate mechanism ready to break the loop open, deep dramatic shadows on ancient walls, representing Python while loop infinite repetition, cinematic lighting, 16:9

什麼是 while 迴圈?

while 迴圈是 Python 的條件驅動型重複語法——每次執行迴圈前先檢查條件,若條件為 True 就執行迴圈內的程式碼,執行完再回頭檢查條件,如此循環直到條件變為 False 才停止。相較於 for 迴圈的「跑完序列就結束」,while 更像是一個不知道要跑幾圈的跑步機:只要你沒按停止鍵(條件不變 False),它就一直跑。

while 的典型使用場景包括:等待使用者輸入正確資料、持倉期間持續監控價格、遊戲主迴圈(反覆等待玩家操作)、以及任何「不知道確切次數,但有明確終止條件」的重複任務。

核心語法:while 與 break 實戰

# === 基本 while 語法 ===
count = 0

while count < 5:             # 條件:count 小於 5 才繼續
    print(f"第 {count} 次執行")
    count += 1               # 每次讓 count 加 1,否則永遠跑不完

# 輸出:
# 第 0 次執行
# 第 1 次執行
# 第 2 次執行
# 第 3 次執行
# 第 4 次執行

# while 等同的 for 迴圈寫法(次數已知時 for 更簡潔)
for i in range(5):
    print(f"第 {i} 次執行")
while 迴圈內部必須有能讓條件最終變為 False 的程式碼(例如遞增計數器、更新狀態變數),否則會形成無窮迴圈,程式永遠無法停止。這是 while 最常見也最危險的錯誤。
# === break:強制跳出迴圈 ===
# 情境:持續讀取使用者輸入,直到輸入 'quit' 為止
while True:                        # 無限迴圈,靠 break 控制退出
    cmd = input("輸入指令(quit 離開):")
    if cmd == 'quit':
        print("程式結束")
        break                      # 跳出 while 迴圈
    print(f"執行指令:{cmd}")

# === continue:跳過本次迭代,繼續下一次 ===
n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue                   # 偶數跳過,不執行 print
    print(n, end=' ')              # 只印奇數:1 3 5 7 9
while True: 搭配 break 是 Python 中非常慣用的模式,讓迴圈的終止條件寫在迴圈內部,比起在 while 條件式中維護複雜布林邏輯更清晰易讀,尤其適合互動式程式與事件驅動循環。

規則與注意事項

規則 正確範例 錯誤範例 / 陷阱
while 行尾必須有冒號 while count < 5: while count < 5 → SyntaxError
迴圈內必須有更新條件的程式碼 count += 1(每次讓條件趨向 False) 忘記更新 → 無窮迴圈,程式卡死
break 只跳出最內層迴圈 巢狀迴圈需逐層 break 或設旗標變數 誤以為 break 能跳出所有層迴圈
continue 跳過本次,不是跳出迴圈 continue 後迴圈繼續執行 誤以為 continue 等同 break
while True 必須確保有 break 出口 至少一個 if ... break 條件 沒有 break → 程式永遠無法停止

常見錯誤與防呆

錯誤一:忘記在迴圈內更新條件變數,造成無窮迴圈

# ❌ 錯誤寫法(count 永遠是 0,條件永遠 True,程式卡死)
count = 0
while count < 5:
    print(count)
    # 忘記寫 count += 1 → 無窮迴圈!

# ✅ 正確寫法:確保每次迭代都更新計數器
count = 0
while count < 5:
    print(count)
    count += 1    # 讓條件最終變為 False

錯誤二:continue 後面的更新語句被跳過

# ❌ 錯誤寫法(continue 跳過了 count += 1,造成無窮迴圈)
count = 0
while count < 5:
    if count == 3:
        continue          # 跳過本次,但 count 沒有被更新!
    print(count)
    count += 1            # 當 count == 3 時這行永遠不執行

# ✅ 正確做法:更新語句放在 continue 之前,或使用 for 迴圈
count = 0
while count < 5:
    count += 1            # 先更新
    if count == 3:
        continue          # 再跳過
    print(count)          # 印出:1 2 4 5

錯誤三:誤以為 break 能跳出所有層巢狀迴圈

# ❌ 誤解:以為 break 跳出所有巢狀迴圈
for i in range(3):
    while True:
        print(f"i={i}")
        break             # 只跳出 while,外層 for 仍繼續執行

# 輸出:i=0  i=1  i=2(for 迴圈仍跑完三次)

# ✅ 若需要跳出外層迴圈,使用旗標變數
found = False
for i in range(3):
    while True:
        if i == 1:
            found = True
            break
        break
    if found:
        break
print(f"在 i={i} 時中止")   # 在 i=1 時中止

進階用法

while-else 子句

Python 的 while 迴圈支援 else 子句,當迴圈條件自然變為 False 而結束(非 break 跳出)時,else 區塊才會執行。這個特性可用來區分「正常結束」與「提前中止」兩種情況。

# while-else:區分正常結束與 break 中止
target = 7
count = 0

while count < 10:
    if count == target:
        print(f"找到目標 {target},提前中止")
        break
    count += 1
else:
    # 只有在條件自然變 False(count >= 10)時才執行
    print("搜尋完畢,未找到目標")

# count 從 0 跑到 7 時觸發 break,else 不執行
# 輸出:找到目標 7,提前中止

# 若 target = 99(不在範圍內)
target = 99
count = 0
while count < 10:
    if count == target:
        break
    count += 1
else:
    print("搜尋完畢,未找到目標")   # 輸出:搜尋完畢,未找到目標

輸入驗證迴圈

while True 搭配 break 是實作輸入驗證的標準模式,持續要求使用者重新輸入,直到提供合法資料為止。

# 持續要求輸入,直到輸入合法的正整數
while True:
    raw = input("請輸入一個正整數:")
    if raw.isdigit() and int(raw) > 0:
        value = int(raw)
        print(f"輸入有效:{value}")
        break
    else:
        print("輸入無效,請重新輸入")

# 互動流程:
# 請輸入一個正整數:abc  → 輸入無效,請重新輸入
# 請輸入一個正整數:-5   → 輸入無效,請重新輸入
# 請輸入一個正整數:42   → 輸入有效:42

量化實戰:持倉監控迴圈

while 迴圈非常適合模擬「持續監控直到觸發出場條件」的策略邏輯,讓每根 K 線都檢查一次是否符合停損或停利條件。

import random   # 模擬價格隨機波動

entry_price = 100.0
stop_loss   = 95.0    # 停損:虧損 5%
take_profit = 110.0   # 停利:獲利 10%
current_price = entry_price
bar = 0

print(f"進場價:{entry_price}")

while True:
    # 模擬每根 K 線價格隨機變動 ±2%
    change = random.uniform(-2, 2)
    current_price = round(current_price * (1 + change / 100), 2)
    bar += 1
    print(f"  K 線 {bar:3d}:{current_price}")

    if current_price <= stop_loss:
        print(f"觸發停損!出場價:{current_price}")
        break
    elif current_price >= take_profit:
        print(f"觸發停利!出場價:{current_price}")
        break
    elif bar >= 100:
        print(f"達到最大持倉 K 線數,強制出場:{current_price}")
        break

煉金坊小叮嚀

while 迴圈是功能強大但也最容易「卡死程式」的語法。我的第一條鐵則:每次寫 while 迴圈,立刻問自己「這個條件在哪裡、由什麼讓它變成 False?」——沒有答案就先別執行。量化開發中我慣用 while True + break 模式來處理「等待信號觸發」的邏輯,這樣終止條件寫在迴圈內部,比在 while 後面維護複雜條件式清晰很多。另外要注意,continue 搭配 while 時特別容易把計數器更新語句意外跳過,形成偽裝成正常程式的無窮迴圈——養成習慣:使用 continue 前,確認計數器或狀態更新語句寫在 continue 之前。

張貼留言

較新的 較舊