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.
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.
以下示範計算 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 置於迴圈內部(具縮排),每次迭代皆會觸發重新賦值為 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.
total = 0 應該修改為多少數值?total = 1。total = 0 be changed to?total = 1.