Chapter 1: Algorithm Design & Basics of Python
第一章:演算法設計與 Python 程式基礎 | S2 ICT Elective
Topic: Algorithms & IPO Cycle
主題:演算法與 IPO 循環
Date: ___________
Key Term 關鍵詞 Algorithm 演算法 解決問題的有序步驟
Q: What is an algorithm?
演算法是什麼?
Key Term 關鍵詞 Dry Run 空運行 理解演算法的過程
Q: Why do we dry run?
為何要空運行?
Key Term 關鍵詞 IPO Cycle 輸入—處理—輸出循環
Q: Name 3 parts of IPO.
說出 IPO 三個部分。
Key Term 關鍵詞 Pseudocode 偽代碼 用簡單語句表達演算法
Key Term 關鍵詞 Flowchart 流程圖 用形狀連線表達演算法
Q: What shape = decision?
什麼形狀代表判斷?
Reminder 提示
Program 程式
= set of instructions
= 一組電腦指令
1.1 Algorithm 演算法
An algorithm is a set of steps for solving a problem in a specified order. 演算法是按照指定順序解決問題的一組步驟。 A program is a set of instructions for a computer. 程式是給電腦執行的一組指令。 Dry run = comprehending an algorithm without running it — tracing purpose & output. 空運行 = 不執行程式,直接推演演算法的目的與輸出。
A. IPO Cycle 輸入—處理—輸出循環
Tool for problem analysis and understanding algorithm structure. 用於問題分析及了解演算法結構的工具。
Part 部分 Role 作用 BMI Example 例子
Input 輸入 Data used by program
程式使用的數據
Weight (kg), Height (m)
Process 處理 Method performed
執行的方法
BMI = Weight ÷ Height²
Output 輸出 Info returned
程式回傳的資訊
BMI value 數值
B. Pseudocode & Flowchart 偽代碼與流程圖
  • Pseudocode — simple words/statements to express algorithm 偽代碼 — 用簡單語句表達演算法
  • Flowchart — specific shapes linked to express algorithm 流程圖 — 用特定形狀連線表達演算法
Element 元素PseudocodeFlowchart Shape 形狀
Start/End 開始/結束—Oval 橢圓形
Process 處理A ← 21Rectangle 長方形
Input/Output 輸入/輸出Input A, BParallelogram 平行四邊形
Decision 判斷if A = B thenDiamond 菱形
Sub-program 子程式ProABCRectangle + lines 矩形加線
C. Trace Table 追蹤表
Helps trace variable values line by line through pseudocode — spot mistakes! 逐行追蹤偽代碼中變數的值,有助發現錯誤!
A ← 2    → A=2
B ← 5    → B=5
A ← B - A → A=3
A ← A * B → A=15
B ← A - B → B=10
Summary 總結 (Page 1)
Algorithm = ordered steps to solve a problem (演算法 = 有序步驟解決問題). IPO: Input → Process → Output. Pseudocode uses words; Flowchart uses shapes. Trace table tracks variable values line by line (追蹤表逐行記錄變數值).
★ Dry run tip:
Fill trace table
column by column!
空運行技巧:
逐欄填寫追蹤表!
1 / 6
1.2 & 1.3 — Python Programs & Basic Concepts
Python 程式與基本程式概念 | S2 ICT Elective
Topic: Python Setup & Variables
主題:Python 設置與變數
Date: ___________
Key Term 關鍵詞 IDE 整合開發環境
Q: What IDE do we use?
我們使用哪個 IDE?
Key Term 關鍵詞 Variable 變數 電腦記憶體中儲存數據的位置
Q: Rules for variable names?
變數命名規則?
Key Term 關鍵詞 Data Types 數據類型 int / float / bool / str
Q: What type is "Hello"?
"Hello" 是什麼類型?
Key Term 關鍵詞 Comment 註解 用 # 開頭,不影響程式運行
Warning ⚠
Reserved words
保留字 (e.g. for,
while, if, print)
CANNOT be used
as variable names!
不可用作變數名!
Tip 提示
Python is case-sensitive!
Python 區分大小寫!
bmi ≠ BMI ≠ Bmi
1.2 From Pseudocode → Python
PseudocodePython
Output "text"
Input length
area ← length * length
print("text")
length = input("...")
area = length * length
Use Thonny IDE (v3.3.10+) to write & run Python programs. 使用 Thonny IDE 編寫及執行 Python 程式。 # Comments — ignored by compiler, improve readability. 以 # 開頭的註解被編譯器忽略,提高可讀性。
1.3A Output Statement 輸出語句
print("Text")      → Text
length = 10
print(length)      → 10
print("Hi", name)  → Hi Sam
1.3B Variables & Data Types 變數與數據類型
Variable = location in computer memory for data storage. 變數 = 電腦記憶體中用來儲存數據的位置。
Type 類型Data 數據Example 例子
intIntegers 整數mark = 98
floatDecimals 小數pi = 3.14
boolTrue / FalseisPrime = True
strCharacters 字元grade = "A"
Variable naming rules 變數命名規則:
  • Start with letter (A-Z, a-z) or underscore _ 以英文字母或下劃線開頭
  • Only letters, numbers, underscore — NO spaces/symbols 只可用字母、數字、下劃線,不可有空格或符號
  • Cannot use reserved words (for, while, if, print…) 不可使用保留字
Python tags data type automatically via assignment (=). Python 透過賦值 (=) 自動標記數據類型。
Summary 總結 (Page 2)
Thonny IDE runs Python. Variables store data; 4 simple types: int, float, bool, str. Rules: start with letter/_, no spaces, no reserved words. # for comments (不影響運行). Python auto-tags data types via = assignment (自動標記數據類型).
Type casting:
int("5") → 5
float("3.14")
類型轉換!
2 / 6
1.3 — Input, Arithmetic & Boolean Expressions
輸入語句、算術運算式與布林運算式 | S2 ICT Elective
Topic: Operators 運算符
Date: ___________
Key Term 關鍵詞 input() function 讀取用戶輸入(回傳字串)
Q: Why use int(input())?
為何用 int(input())?
Key Term 關鍵詞 Arithmetic Operators
算術運算符
+ − * / // % **
Q: What does // do?
// 的作用?
Key Term 關鍵詞 Boolean Expression
布林運算式
結果只有 True 或 False
Q: Diff between = and ==?
= 與 == 的分別?
Key Term 關鍵詞 Precedence 優先次序 PEMDAS-like rules in Python
Q: Which has highest precedence?
哪個優先次序最高?
Warning ⚠
== (compare 比較)
≠ = (assign 賦值)
Confusing these
causes bugs! 混淆
會導致程式錯誤!
1.3C Input Statement 輸入語句
name = input()                 # → str
mark = int(input())           # → int
name = input("Your name: ")  # with prompt
input() always returns a string. Use int() or float() to convert. input() 永遠回傳字串。用 int() 或 float() 轉換類型。
1.3D Arithmetic Operators 算術運算符
Operation 運算OperatorExampleResult
Addition 加+3 + 47
Subtraction 減−10 − 37
Multiplication 乘*3 * 412
Division 除/10 / 42.5
Integer division 整除//10 // 42
Modulus 模數%10 % 42
Exponent 指數**2 ** 38
1.3E Boolean Expressions 布林運算式
Relational operators 關係運算符: ==   !=   <   <=   >   >= 結果為 True 或 False(布林類型)
Boolean (Logical) operators 布林(邏輯)運算符:
  • and — both must be True 兩者均為 True
  • or — at least one True 至少一個為 True
  • not — reverses True/False 反轉結果
Precedence order 優先次序 (highest → lowest): 括號 → ** → 負號 → * / // % → + − → 比較 → not → and → or
# Example: −1 + 2 * 2 + (2 ** (3 ** 2))
# = −1 + 4 + 512 = 515
Summary 總結 (Page 3)
input() returns str — convert with int()/float(). Arithmetic: + − * / // % **. // = integer division (商); % = modulus (餘數). Boolean expressions → True/False. == compares (比較); = assigns (賦值). Precedence: () → ** → * / → + − → comparisons → not → and → or.
10 // 3 = 3
10 % 3 = 1
整除 = 商
模數 = 餘數
3 / 6
1.4 — Control Structures: Selection
控制結構:選擇 | S2 ICT Elective
Topic: if / elif / else
主題:條件語句
Date: ___________
Key Term 關鍵詞 Control Structure
控制結構
Sequence / Selection / Iteration
順序 / 選擇 / 迭代
Key Term 關鍵詞 Selection 選擇 if / elif / else
Q: When use elif vs else?
何時用 elif?
Key Term 關鍵詞 Indentation 縮排 顯示程式碼的邏輯結構
Q: How many spaces for indent?
縮排用多少空格?
Tip 提示
In Thonny:
Tab = add indent
Shift+Tab = remove
Tab 鍵增加縮排
Shift+Tab 移除
See Also 參見
→ Page 3: Boolean expressions
→ 第3頁:布林運算式
Three Types of Control Structures 三種控制結構
  • Sequence 順序 — execute in order of writing 按書寫順序執行
  • Selection 選擇 — decide which statements to run 決定執行哪些語句
  • Iteration 迭代 — repeat statements 重複執行語句 (→ Page 5)
Selection: if / elif / else 選擇語句
Type 類型Python Syntax
if-then if (condition):
    ("then" body)
if-then-else if (condition):
    ("then" body)
else:
    ("else" body)
if-elif if (cond 1):
    (body 1)
elif (cond 2):
    (body 2)
else:
    (else body)
Indentation 縮排
Indentation is critical in Python — shows logical structure & which body belongs to which branch. 縮排在 Python 中非常重要,顯示邏輯結構及語句屬於哪個分支。 else must align with its corresponding if. else 必須與對應的 if 對齊。
if mark >= 50:
    print("Pass")   # indented
    print("Promoted")
else:
    print("Fail")
    print("Repeated")
Combining Boolean Operators 組合布林運算符
Use and / or to simplify multiple conditions: 使用 and / or 簡化多個條件:
# if X > 10 OR Y > 10 → Z = X + Y
if X > 10 or Y > 10:
    Z = X + Y
else:
    Z = Z + 10
Summary 總結 (Page 4)
3 control structures: Sequence (順序), Selection (選擇), Iteration (迭代). Selection uses if / elif / else with Boolean condition. Indentation (縮排) is MANDATORY in Python. Combine conditions with and / or to simplify if-elif chains (簡化條件鏈).
if ← condition
elif ← next check
else ← default
記住縮排!
4 / 6
1.4 — Control Structures: Iteration (Loops)
控制結構:迭代(循環)| S2 ICT Elective
Topic: for loop / while loop
主題:for 循環 / while 循環
Date: ___________
Key Term 關鍵詞 Iteration 迭代 = Loop 循環控制結構
Q: What is loop body?
什麼是循環體?
Key Term 關鍵詞 for loop 用於已知次數的循環
range(first, last)
Q: range(0,5) gives how many iterations?
產生多少次迭代?
Key Term 關鍵詞 while loop 條件為 True 時持續循環
Q: When use while vs for?
何時用 while?
Key Term 關鍵詞 Loop body 循環體 被重複執行的語句
Warning ⚠
Infinite loop!
無限循環!
while True:
→ must have
break condition
必須有終止條件!
Iteration = Loop Control Structure 迭代 = 循環控制結構
Repeatedly executes statement(s) until loop condition is no longer True. 重複執行語句,直到循環條件不再為 True。 The repeated statement(s) = loop body 循環體.
for Loop — Known Number of Iterations 已知次數
for i in range(first_value, last_value):
    loop body (loop_body)

# Example: print 0 to 4
for i in range(0, 5):
    print(i)  # 0, 1, 2, 3, 4
range(0, 5) → i takes values 0, 1, 2, 3, 4 (last value excluded 不包括最後值). range(first, last):i 取 first 至 last-1 的值。
i = first
→
i < last?
Yes→
loop body
→
i = i+1
while Loop — Condition-Based 條件型循環
while (condition):
    loop body

# Example: count down
n = 10
while n > 0:
    print(n)
    n = n - 1
Use while when number of iterations is unknown in advance. 當不知道需要循環多少次時,使用 while 循環。
for vs while 比較
for loopwhile loop
Use when 用於Known iterations 已知次數Unknown iterations 未知次數
CounterAuto (range) 自動Manual update 手動更新
Risk 風險Low 低Infinite loop 無限循環
Summary 總結 (Page 5)
Iteration = loop: repeats loop body until condition is False. for loop: range(first, last) — known iterations (已知次數). while loop: runs while condition is True — unknown iterations (未知次數). Always avoid infinite loops (避免無限循環)!
range(0,5)
= 0,1,2,3,4
NOT 5! 不包括5
記住!
5 / 6
1.5 — Data Structures: Lists & 1D Arrays
數據結構:列表與一維陣列 | S2 ICT Elective
Topic: Lists, Index, Counting
主題:列表、索引、計算
Date: ___________
Key Term 關鍵詞 Data Structure 數據結構 幫助組織數據以便使用
Key Term 關鍵詞 List 列表 Python 的一維陣列
一組連續變數
Q: What is age[0]?
age[0] 代表什麼?
Key Term 關鍵詞 Index 索引 從 0 開始的位置編號
Q: Index of 1st item?
第一個項目的索引?
Key Term 關鍵詞 Counting 計算
Accumulating 累積
列表常用算法
Reminder 提示
Index starts at 0!
索引從 0 開始!
age[0] = 1st item
age[1] = 2nd item
See Also 參見
→ Page 5: for loop with range
→ 第5頁:for 循環
1.5A Data Structure 數據結構
Data structure helps organise data for easier use. 數據結構幫助組織數據以便使用。 1D Array (一維陣列) = simple linear structure storing data sequentially. 一維陣列 = 簡單的線性結構,按順序儲存一組數據。 In Python, use list instead of traditional arrays. Python 使用列表 (list) 代替傳統陣列。
List Structure 列表結構
age = [8, 21, 16, 55, 80, 28, 49, 52, 17, 25]
# [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] ← index 索引
# age[0] = 8   age[1] = 21   age[9] = 25
Use index to find specific item/element. 用索引找到特定的項目/元素。索引從 0 開始!
Finding Sum & Average 求和與平均值
num = [15, 10, 5, 25, 20, 30]
total = 0
for i in range(0, 6):
    total = total + num[i]  # accumulating 累積
print(total)               # → 105
avg = total / 6
print(avg)                 # → 17.5
Key Algorithms with Lists 列表常用算法
  • Counting 計算 — count items meeting a condition 計算符合條件的項目數
  • Accumulating 累積 — sum up values 累加數值 (total = total + item)
  • Finding max/min — compare each element 比較每個元素
  • Searching 搜尋 — check if value exists 檢查數值是否存在
Lists + for loops = powerful combination for data processing! 列表 + for 循環 = 數據處理的強大組合!
Summary 總結 (Page 6) — Chapter Review 章節回顧
List = Python's 1D array. Index starts at 0 (索引從0開始). Access: list[index]. Use for loop + accumulating variable (累積變數) to find sum/average. Ch.1 covers: Algorithm→IPO→Pseudocode/Flowchart→Trace Table→Python Basics→Variables→Operators→Selection→Iteration→Lists.
Chapter 1 done!
第一章完成!
Review all 6 pages
before the exam!
考試前溫習!
6 / 6