Learning Objectives 學習目標
4 Goals 四大目標
Q: Name 3 control structures.
說出三種控制結構。
Key Term 關鍵詞
Nested Structure
嵌套結構
將一個結構放入另一個結構
Q: What is nested structure?
嵌套結構是什麼?
Key Term 關鍵詞
Nested Conditional
Statement 嵌套條件語句
根據前一條件的結果決定是否進入另一條件語句
Key Term 關鍵詞
3 Control Structures
三種控制結構
順序 / 選擇 / 迭代
Q: Which structure repeats?
哪種結構重複執行?
Tip 提示
Nested = placed
inside another
嵌套 = 放入另
一個結構之內
Application 應用
→ 2D arrays + nested loops
= image manipulation!
→ 二維陣列 + 嵌套循環
= 圖像處理!
Chapter 3 Learning Objectives 學習目標
- Understand how to use nested control structures
了解如何使用嵌套控制結構
- Integrate and apply various control structures to design solutions
綜合運用各種控制結構設計解決方案
- Evaluate algorithms by efficiency, correctness & appropriateness
按效率、正確性和適切性評估演算法
- Select appropriate algorithm based on complexity, data structures & trade-off
根據複雜性、數據結構及取捨選擇適當演算法
3.1 Nested Control Structures 嵌套控制結構
Placing a structure inside another = nested structure 嵌套結構.
將一個結構放入另一個結構之內,稱為嵌套結構。
A nested conditional statement 嵌套條件語句 decides whether to enter another conditional statement based on the result of the previous condition.
嵌套條件語句根據前一條件的結果,決定是否進入另一條件語句。
Two Forms of Nested if 嵌套 if 的兩種形式
| Form 形式 |
Python Code |
Notes 備注 |
if-elif chain 鏈式 elif |
if (c1): body1 elif (c2): body2 else: body3 |
Conditions checked in sequence 按順序 檢查條件 |
Truly nested 真正嵌套 |
if (c1): if (c2): body2 else: if (c3): body3 |
Inner if inside outer branch 內部 if 在外部 分支之內 |
Key: A conditional can be nested in the else branch OR any other branch.
條件語句可嵌套在 else 分支或任何其他分支中。
Triangle Example 三角形例子 (Checkpoint 3.1)
Input: 3 side lengths a, b, c → Classify triangle type:
輸入三條邊長,判斷三角形類別:
- Equilateral 等邊三角形 — all 3 sides equal (三邊相等)
- Isosceles 等腰三角形 — exactly 2 sides equal (兩邊相等)
- Scalene 不等邊三角形 — all sides different (三邊不等)
- Invalid 不能構成三角形 — any 2 sides sum ≤ third side
Summary 總結 (Page 1)
Nested structure = placing one structure inside another (嵌套結構 = 將一結構放入另一結構).
Nested conditional: inner if runs based on outer condition result (內部 if 根據外部條件結果執行).
Two forms: elif chain (鏈式) vs truly nested (真正嵌套). Indentation is critical! (縮排非常重要)
3 control structures:
Sequence 順序
Selection 選擇
Iteration 迭代
1 / 6
Key Term 關鍵詞
Nested Loop 嵌套循環
將一個循環放入另一個循環
Q: What is outer/inner loop?
什麼是外/內循環?
Key Term 關鍵詞
Outer Loop 外循環
控制內循環執行的次數
Key Term 關鍵詞
Inner Loop 內循環
每次外循環執行時,
內循環完整執行一遍
Q: If outer=2, inner=3,
how many total?
總共執行多少次?
Formula 公式
Total inner reps
總內循環次數
= outer reps
× inner reps
外循環次數 × 內循環次數
Analogy 類比
Clock 時鐘:
Minute hand = outer loop
Second hand = inner loop
分針 = 外循環
秒針 = 內循環
3.2 Nested Loop 嵌套循環
Placing a loop inside another loop = nested loop 嵌套循環.
將一個循環放入另一個循環之內,稱為嵌套循環。
Pseudocode
Outer loop 外循環
for i from 0 to 1
Output i
Inner loop 內循環
for j from 0 to 2
Output j
Python
for i in range(0, 2):
print(i)
for j in range(0, 3):
print(j)
Trace Table for Nested Loop 嵌套循環追蹤表
| Line 行 | i | j | Output 輸出 | Note 備注 |
| for i ← 0 | 0 | | | Outer body (i=0) 外循環體 |
| Output i | | | 0 |
| for j ← 0 | | 0 | 0 | |
| for j ← 1,2 | | 1,2 | 1, 2 | |
| for i ← 1 | 1 | | 1 | Outer body (i=1) |
| for j ← 0,1,2 | | 0,1,2 | 0, 1, 2 | |
Each time outer loop body executes → inner loop body executes 3 times.
每次外循環體執行 → 內循環體執行 3 次。
Total inner repetitions = 2 × 3 = 6
Counting Repetitions 計算重複次數
| Code | Outer reps 外 | Inner reps 內 | Total 總計 |
| for i 0→1, for j 0→2 | 2 | 3 | 6 |
| for i 1→5, for j 1→6 | 4 | 5 | 20 |
| range(0,5), range(0,10) | 5 | 10 | 50 |
Example: Draw a Square of * (Example 3.1)
L = int(input()) # e.g. L=5
for i in range(0, L): # outer: rows 行
for j in range(0, L): # inner: cols 列
print("*", end="")
print() # newline 換行
print("*", end="") — suppresses newline, prints on same line (不換行).
end="" 參數取消換行,使 * 在同一行輸出。
Summary 總結 (Page 2)
Nested loop = loop inside loop (嵌套循環 = 循環中的循環).
Each outer iteration → inner loop runs COMPLETELY (每次外循環 → 內循環完整執行一遍).
Total reps = outer × inner (總次數 = 外 × 內). Clock analogy: minute=outer, second=inner.
print("*", end="") keeps output on same line (end="" 使輸出在同一行).
range(0, 2)
= 0, 1 → 2 reps
range(0, 3)
= 0,1,2 → 3 reps
記住!
2 / 6
Key Term 關鍵詞
2D Array 二維陣列
rows × columns 的格狀結構
Q: How to access num[i][j]?
如何存取 num[i][j]?
Key Term 關鍵詞
Initialisation 初始化
在存取前先建立列表並賦予預設值
Q: Why must we initialise?
為何必須初始化?
Key Term 關鍵詞
Index 索引
num[i][j]
i = row 行, j = column 列
Tip 提示
Outer loop → rows 行
Inner loop → cols 列
外循環 → 行
內循環 → 列
See Also 參見
→ Page 2: Nested loops
→ 第2頁:嵌套循環
→ Page 4: Applications
→ 第4頁:應用
3.3 Accessing 2D Array with Nested for Loop 用嵌套循環存取二維陣列
Use nested for loop to access items in a 2D array one by one.
用嵌套 for 循環逐一存取二維陣列中的項目。
# Access all items row by row 逐行存取
for i in range(0, 3): # rows i=0,1,2
for j in range(0, 4): # cols j=0,1,2,3
num[i][j] = i * j # assign value 賦值
Note: Swapping outer/inner loop order changes the traversal direction but not the result when accessing all items.
注意:交換內外循環的順序會改變遍歷方向,但存取所有項目的結果不變。
Initialisation of 2D List 二維列表的初始化
Before accessing items, must create the list and assign default values = initialisation 初始化.
在存取項目前,必須先建立列表並賦予預設值,此過程稱為初始化。
# Initialise 3×6 list with 0s 初始化 3×6 列表
num = []
for i in range(0, 3): # ① add rows 增加行
num = num + [[]]
for j in range(0, 6): # ② add cols 增加列
num[i] = num[i] + [0]
num[i][j] = i * j # assign 賦值
Example 3.2 — Bookshelf Total 書架總書數
B[i][j] stores number of books in storage unit (i,j). Find total books.
B[i][j] 儲存位置 (i,j) 的書本數量,求總書數。
total = 0
for i in range(0, 3): # 3 rows 行
for j in range(0, 6): # 6 cols 列
total = total + B[i][j]
print(total)
Pattern: outer loop = rows (行), inner loop = columns (列). Works for any m×n array.
模式:外循環 = 行,內循環 = 列。適用於任何 m×n 陣列。
2D Array Index Diagram 二維陣列索引圖
| i \ j | j=0 | j=1 | j=2 | j=3 |
| i=0 | num[0][0] | num[0][1] | num[0][2] | num[0][3] |
| i=1 | num[1][0] | num[1][1] | num[1][2] | num[1][3] |
| i=2 | num[2][0] | num[2][1] | num[2][2] | num[2][3] |
Summary 總結 (Page 3)
2D array accessed by num[i][j] — i=row (行), j=col (列). Nested for: outer=rows, inner=cols.
Initialisation (初始化) = create list + assign default values BEFORE accessing items.
Pattern for sum: total=0 → nested for → total = total + array[i][j] → print(total).
num[i][j]
i = row 行
j = col 列
Always init first!
先初始化!
3 / 6
Key Concept 核心概念
Integrated Control
綜合控制結構
三種結構可組合使用
Q: Name all 3 structures.
說出三種控制結構。
Key Term 關鍵詞
Control Flow
控制流程
語句執行的順序
Key Term 關鍵詞
Multi-layered Nested
多層嵌套結構
控制結構 + 數據結構組合
Q: How many while loops
in Example 3.3?
例3.3有幾個while循環?
Warning ⚠
Array index out
of range! 索引越界!
Always check:
0 ≤ i ≤ max
0 ≤ j ≤ max
See Also 參見
→ Page 3: 2D arrays
→ Page 5: Comparison
→ 第3頁:二維陣列
→ 第5頁:演算法比較
3.4 Integrated Application 綜合應用
Control structures can be combined with data structures (1D & 2D arrays) to form multi-layered nested structures.
控制結構可與數據結構(一維及二維陣列)組合,形成多層嵌套結構。
| Structure 結構 | Role 作用 |
| Sequence 順序 | Execute statements in order 按順序執行 |
| Selection 選擇 | Decide which path 決定執行哪個分支 |
| Iteration 迭代 | Repeat statements 重複執行語句 |
Example 3.3 — Agricultural Robot 農業機器人 (while + for + if)
F[y,x] = 1 (sow 播種) or 0 (skip 跳過) in 10×10 farm grid.
F[y,x] 儲存 10×10 農場格的播種指令(1=播種,0=跳過)。
y ← 0
while y < 10 do # outer while 外while
x ← 0
while x < 10 do # inner while 內while
for i from y to y+n-1 # nested for 嵌套for
for j from x to x+n-1
if i <= 9 and j <= 9 then # boundary check 邊界檢查
F[i,j] ← 1
x ← x + (n*2)
y ← y + (n*2)
Analysis 分析:
- Inner nested for (lines 5-7): creates n×n square at position (x,y)
嵌套 for 循環:在位置 (x,y) 建立 n×n 的播種方塊
- Inner while (lines 4-9): creates a row of n×n squares, spaced n apart
內 while 循環:建立一行 n×n 方塊,間距為 n
- Outer while (lines 2-10): creates multiple rows of squares
外 while 循環:建立多行方塊
- Boundary check: if i ≤ 9 and j ≤ 9 prevents index out of range
邊界檢查:防止索引越界(陣列索引不可超出範圍)
Summary 總結 (Page 4)
Any complex program = combination of Sequence + Selection + Iteration (順序+選擇+迭代).
Pair with 1D/2D arrays for multi-layered nested structures (多層嵌套結構).
ALWAYS check array index boundaries (始終檢查陣列索引邊界): 0 ≤ index ≤ max.
while+for+if nested together → powerful solution design (強大的解決方案設計).
Boundary check!
邊界檢查!
if i<=9 and
j<=9 then...
防止索引越界!
4 / 6
Key Term 關鍵詞
Algorithm Comparison
演算法比較
選擇最正確、適切的解決方案
Q: 5 criteria for comparison?
比較演算法的5個標準?
Key Term 關鍵詞
Time Complexity
時間複雜度
步驟越多 → 時間越長
Q: More steps = ?
步驟更多 = ?
Key Term 關鍵詞
Space Complexity
空間複雜度
佔用資源越多 → 空間複雜度越高
5 Criteria 五個標準
① Correctness 正確性
② Appropriateness 適切性
③ Steps/Time 步驟/時間
④ Resource usage 資源使用
⑤ Complexity 複雜度
⑥ Data structures 數據結構
Trade-off 取捨
Q: Can an algorithm be fast
but use more memory?
演算法可以快但
佔更多記憶體嗎?
3.5 Algorithm Comparison 演算法比較
A problem can often be solved by several algorithms — each with merits & demerits.
一個問題通常可用多個演算法解決,各有優缺點。
Compare algorithms to select the most correct and appropriate solution.
比較演算法以選擇最正確、最適切的解決方案。
Comparison Criteria 比較標準
| Criterion 標準 | Meaning 含義 | Impact 影響 |
Correctness 正確性 |
Produces correct output 輸出正確結果 |
Most important 最重要 |
Appropriateness 適切性 |
Handles all cases 處理所有情況 |
Covers edge cases 涵蓋邊界情況 |
Steps / Time 步驟/時間 |
Number of operations 運算步驟數量 |
↑ steps → ↑ time 步驟多→時間長 |
Resource usage 資源使用 |
Memory, CPU used 記憶體、CPU用量 |
Space complexity 空間複雜度 |
Data structures 數據結構 |
Type of arrays used 使用的陣列類型 |
Affects complexity 影響複雜度 |
Checkpoint 3.4 — Missing Item (3 Algorithms) 缺失項目(三種演算法)
Box A contains items A to A+9. Array C has 9 items (one missing). Find missing item.
箱子 A 應有 A 至 A+9 共10件物品。陣列 C 有9件,找出缺失的一件。
| Algorithm 演算法 | Method 方法 | Advantage 優點 |
| Algorithm 1 |
Sum expected − sum actual 預期總和 − 實際總和 |
Fewer steps 步驟少 More efficient 更高效 |
| Algorithm 2 |
For each expected item, search in array 逐一搜尋 |
Can find duplicates 可找重複項 |
| Algorithm 3 |
Mark found items in boolean array 用布林陣列標記 |
More readable 可讀性更高 |
Algorithm 1 most efficient (fewer steps). Algorithms 2 & 3 can handle special case: finding duplicates (重複項).
演算法1最高效(步驟最少)。演算法2和3可處理特殊情況:找出重複項目。
Summary 總結 (Page 5)
Compare algorithms by: Correctness, Appropriateness, Steps/Time, Resource usage, Complexity, Data structures (正確性、適切性、步驟/時間、資源、複雜度、數據結構).
Time complexity (時間複雜度): more steps → longer time. Space complexity (空間複雜度): more resources → higher.
Trade-off: fast algorithm may use more memory (快速演算法可能佔用更多記憶體).
Alg 1: sum trick
最少步驟!
Alg 2 & 3: can
find duplicates
可找重複項!
5 / 6
Review 複習
Chapter Glossary
章節詞彙
Q: Define all 4 terms.
定義全部4個詞彙。
Key Pattern 重要模式
Sum of 2D Array
二維陣列求和
total=0 → nested for → accumulate
Key Pattern 重要模式
Draw * Pattern
繪製 * 圖案
outer=rows, inner=cols
print("*",end="")
Q: How to print a triangle?
如何輸出三角形?
Key Pattern 重要模式
Search in 2D
二維搜尋
nested for + if condition
嵌套for + 條件判斷
Exam Tip 考試技巧
Always trace with
trace table! 用追蹤表!
Check i,j,output
each iteration
每次迭代檢查i,j,輸出
Chapter 3 Glossary 詞彙表
| English Term | Chinese 中文 | Definition 定義 |
| initialisation | 初始化 | Create list & assign default values before access 存取前建立列表並賦予預設值 |
| nested conditional statement | 嵌套條件語句 | if inside another if/else 在另一個if/else中的if |
| nested loop | 嵌套循環 | Loop inside another loop 循環中的循環 |
| nested structure | 嵌套結構 | Structure placed inside another 結構放入另一結構 |
Key Code Patterns 重要代碼模式
① Sum 2D Array 二維陣列求和
total = 0
for i in range(0,R):
for j in range(0,C):
total+=arr[i][j]
print(total)
② Draw Rectangle 繪製矩形
for i in range(0,H):
for j in range(0,W):
print("*",end="")
print()
③ Draw Triangle 繪製三角形
for i in range(0,H):
for j in range(0,i+1):
print("*",end="")
print()
④ Search 2D 二維搜尋
found = False
for i in range(0,R):
for j in range(0,C):
if arr[i][j]==x:
found=True
Chapter 3 Mind Map 思維導圖
Ch.3 Advanced
Control Structures
高級控制結構
3.1 Nested if
嵌套條件語句
3.2 Nested Loops
嵌套循環
3.3 2D Arrays
二維陣列
3.4 Integration
綜合應用
3.5 Comparison
演算法比較
Summary 總結 (Page 6) — Full Chapter Review 全章回顧
Ch.3: Nested if (嵌套條件) → Nested loops (嵌套循環) → 2D arrays (二維陣列) → Integration (綜合) → Comparison (比較).
Key: total=outer×inner reps; init 2D list before use; boundary check always; compare algorithms by 5 criteria.
Exam: use trace table (追蹤表) to dry-run nested loops step by step!
EC3 done! 完成!
Review all 6 pages
before exam!
考試前溫習
全部6頁!
6 / 6