Python 迴圈邏輯:倒數與累加 Python Loops: Countdown & Accumulation

模組一:倒數計時 Module 1: The Countdown

學習目標:Learning Objective: 了解如何使用 for 迴圈與 range() 函數控制數值遞減,並區別迴圈內部與外部的程式碼執行順序。 Understand how to use the for loop and range() function for decrementation, and distinguish execution orders inside and outside the loop.

此程式碼將執行從 10 至 1 的倒數。當迴圈迭代完全結束後,才會執行印出字串的指令。 This code counts down from 10 to 1. The string print command executes only after the loop iteration is completely finished.

for i in range(10, 0, -1): print(i) # 具縮排:位於迴圈內部,依迭代次數重複執行Indented: Inside the loop, executes repeatedly print("Happy New Year!") # 無縮排:位於迴圈外部,於迴圈結束後執行一次Unindented: Outside the loop, executes once at the end
10
Click the button below to execute 點擊下方按鈕開始執行
💡 技術釐清:range() 參數設定 Technical Clarification: range() parameters Python 的 range(start, stop, step) 函數設計為不包含終點值 (Exclusive)。若需輸出數值 1,stop 參數必須設定為 0。若設為 range(10, 1, -1),執行至 2 即會停止。 Python's range(start, stop, step) is designed to be Exclusive at the stop value. To output 1, the stop parameter must be 0. If set to range(10, 1, -1), execution halts at 2.

模組二:變數累加 Module 2: Variable Accumulation

學習目標:Learning Objective: 建立初始變數,並透過迴圈迭代將新數值逐步累加覆寫至該變數中。 Initialize a variable and progressively accumulate and overwrite values into it through loop iteration.

以下示範計算 1 至 5 的總和。變數 total 必須在迴圈啟動前宣告並賦值為 0。 Demonstrating the sum from 1 to 5. The variable total must be declared and assigned 0 before the loop starts.

total = 0 # 迴圈前:宣告並初始化累加變數Before loop: Initialize accumulator variable for i in range(1, 6): total = total + i # 迴圈內:將目前的 i 數值累加至 totalInside loop: Add current i to total print(total) # 迴圈後:輸出最終計算結果After loop: Output final result
當前 i 值Current i
1
+
變數 totalVariable total 0
初始狀態:total = 0 Initial State: total = 0
💡 邏輯錯誤:於迴圈內初始化變數 Logical Error: Initialization inside loop 若將 total = 0 置於迴圈內部(具縮排),每次迭代皆會觸發重新賦值為 0 的指令,導致變數無法保留先前的累加資料,最終結果僅會輸出最後一次的 i 值。 If total = 0 is placed inside the loop (indented), each iteration triggers a reassignment to 0, destroying previously accumulated data. The final output will only equal the last value of i.

課堂總結與延伸推導 Consolidation & Extension

📌 技術重點 (Key Takeaways)Key Takeaways
  • 縮排 (Indentation) 決定執行範圍: Python 嚴格依賴縮排界定程式碼區塊,縮排內的指令受迴圈控制,縮排外則不受影響。 Indentation defines scope: Python strictly relies on indentation to define code blocks. Indented code is controlled by the loop; unindented code is not.
  • 變數生命週期: 累加操作必須在迴圈外部宣告初始變數,以確保其數值狀態能在多次迭代中持續保留與更新。 Variable Lifecycle: Accumulation requires declaring the initial variable outside the loop to ensure its state is maintained across iterations.