跳轉至

建立 2026-11-12 更新 2026-11-12 SL HL

B2.3 程式結構:選擇、迴圈與函式

程式結構(Programming constructs)是組成所有程式的三種基本控制流程:循序(sequence)、選擇(selection)與重複(iteration),再加上用來組織程式的函式(function)與例外處理。掌握這些結構,就能寫出 Paper 2 要求的任何演算法。

如何用選擇結構做判斷?

選擇(selection)依條件決定執行哪段程式。

score = int(input("分數:"))
if score >= 7:
    grade = "優秀"
elif score >= 4:
    grade = "及格"
else:
    grade = "不及格"
print(grade)
Scanner sc = new Scanner(System.in);
int score = sc.nextInt();
String grade;
if (score >= 7) {
    grade = "優秀";
} else if (score >= 4) {
    grade = "及格";
} else {
    grade = "不及格";
}
System.out.println(grade);

條件的順序很重要:先檢查 score >= 4 的話,7 分也會被判為「及格」。

迴圈有哪幾種?

迴圈 使用時機 例子
計數迴圈(count-controlled) 事先知道次數 Python for i in range(10);Java for (int i = 0; i < 10; i++)
條件迴圈,前測(pre-condition) 次數未知,先檢查條件,可能一次都不執行 while
條件迴圈,後測(post-condition) 至少執行一次再檢查條件 Java do { } while (...);Python 用 while True + break
# 計數迴圈:1 到 10 的總和
total = 0
for i in range(1, 11):
    total += i

# 條件迴圈:一直輸入直到密碼正確
password = ""
while password != "ib2027":
    password = input("密碼:")
int total = 0;
for (int i = 1; i <= 10; i++) {
    total += i;
}

String password;
do {
    password = sc.nextLine();
} while (!password.equals("ib2027"));

巢狀迴圈

迴圈裡面還有迴圈,常用於二維陣列或產生組合。外層每執行一次,內層就完整執行一輪。

for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end="\t")
    print()

為什麼要寫函式?

函式(function,Java 中稱為方法 method)把一段可重複使用的程式包起來,好處是:

  • 模組化:每個函式只做一件事,程式更容易閱讀與測試。
  • 重複使用:寫一次,多處呼叫。
  • 抽象化:呼叫者只需要知道輸入與輸出,不必知道內部細節。
def average(numbers):
    """回傳串列的平均值;空串列回傳 0。"""
    if len(numbers) == 0:
        return 0
    return sum(numbers) / len(numbers)

print(average([5, 6, 7]))   # 6.0
public static double average(int[] numbers) {
    if (numbers.length == 0) {
        return 0;
    }
    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    return (double) sum / numbers.length;
}

參數、回傳值與變數範圍

  • 參數(parameter):函式定義中的變數;引數(argument):呼叫時傳入的實際值。
  • 回傳值(return value):函式計算後交回給呼叫者的結果。沒有回傳值的函式在 Java 中標為 void。
  • 區域變數(local variable):只在函式內有效,函式結束就消失。全域變數(global variable):整個程式都能存取,但容易被意外修改,應盡量少用。

如何處理例外?

例外處理(exception handling)讓程式遇到執行期錯誤時不會直接崩潰,而是用預先寫好的方式處理。

try:
    age = int(input("年齡:"))
    ratio = 100 / age
except ValueError:
    print("請輸入數字")
except ZeroDivisionError:
    print("年齡不能是 0")
else:
    print(ratio)
finally:
    print("結束")
try {
    int age = Integer.parseInt(sc.nextLine());
    int ratio = 100 / age;
    System.out.println(ratio);
} catch (NumberFormatException e) {
    System.out.println("請輸入數字");
} catch (ArithmeticException e) {
    System.out.println("年齡不能是 0");
} finally {
    System.out.println("結束");
}

推薦影音

程式設計基礎:敘述與函式

簡述:說明條件判斷、迴圈與函式如何讓程式結構化,並解釋為什麼要把程式拆成函式,對應本頁三大結構與函式兩節。

軟體工程

簡述:Crash Course 介紹大型程式如何用函式、物件與模組化分工,以及版本控制、測試的觀念,能幫助理解為什麼要好好組織程式。

練習題

練習 1:選擇結構

寫一個函式 ticket_price(age):12 歲以下 100 元、65 歲以上 120 元、其他 250 元。

參考答案
def ticket_price(age):
    if age < 12:
        return 100
    elif age >= 65:
        return 120
    else:
        return 250
練習 2:迴圈選擇

下列情境各適合哪種迴圈:(a) 印出 1 到 100;(b) 讀取感測器數值直到溫度超過 80 度;(c) 顯示選單並讀取選項,至少要顯示一次。

參考答案

(a) 計數迴圈 for;(b) 前測條件迴圈 while;(c) 後測條件迴圈(Java do...while,Python while True 搭配 break)。

練習 3:巢狀迴圈

寫程式印出以下圖形(n = 4):

*
**
***
****
參考答案
n = 4
for i in range(1, n + 1):
    line = ""
    for j in range(i):
        line += "*"
    print(line)
練習 4:找出邏輯錯誤

以下函式要找出串列中的最小值,但結果有時不對。找出錯誤並修正。

def find_min(nums):
    smallest = 0
    for n in nums:
        if n < smallest:
            smallest = n
    return smallest
參考答案

smallest 初始值設為 0,若所有數字都大於 0(例如 [5, 3, 8]),會錯誤回傳 0。應改為 smallest = nums[0]。

練習 5:例外處理

修改練習 1,讓使用者從鍵盤輸入年齡;輸入非數字或負數時,要求重新輸入。

參考答案
while True:
    try:
        age = int(input("年齡:"))
        if age < 0:
            print("年齡不能是負數")
            continue
        break
    except ValueError:
        print("請輸入整數")

print(ticket_price(age))