← 返回大綱
進階

第 1~5 章
進階情境題庫

先用第 1~5 章暖身,學過新工具後再進入情境題

開始之前

這份題庫分成 3 個階段

1. 暖身拖拉

只用第 1~5 章已經講過的語法,先把跨章節思路練熟。

2. 新工具小教學

sum()、.get()、.split() 等前 5 章沒完整講過的內容,都會先看範例再用。

3. 進階情境題

題目會標示用到的觀念;遇到「新工具」時,可以往前回看小教學,不需要用猜的。

30 分鐘建議路線:暖身 4 題(8~10 分)→ 新工具 4 頁(8 分)→ 應用題第 3、6、7、8 題(12~14 分)。其他應用題與 ★★★ 挑戰題留作加練或作業。
提醒

「執行看看 ▶」需要先在 Playground 設定過伺服器。 就算拼錯也可以跑跑看,錯誤訊息會告訴你哪裡不對。

暖身組

先用已學過的觀念

暖身第 1 題

依商品名稱查價並加總

已學過:list · dict · for · 累加

menu = {"蛋餅": 35, "奶茶": 25} order = ["蛋餅", "奶茶"] total = 0 for item in : total += menu[] print(total)
order menu item total
60
迴圈要走訂單 order;當前的 item 是字典 menu 的 key。
暖身第 2 題

不用新工具算平均

已學過:函式 · for · len · return

def average(scores): total = 0 for score in : total += score return total len(scores) print(average([70, 80, 90]))
scores score total / // %
80.0
先用 for 逐個累加,最後再用總和 / 數量。下一階段會看到更短的寫法。
暖身第 3 題

候選人都已知的計票

已學過:dict · for · +=

votes = ["A", "B", "A"] count = {"A": 0, "B": 0} for vote in votes: count[] 1 print(count)
vote votes "vote" += -= ==
{'A': 2, 'B': 1}
vote 是這一圈拿到的值。這裡先把 A、B 都設成 0,所以可以直接加 1。
暖身第 4 題

逐字檢查母音

已學過:字串 · for · if · or

text = "apple" count = 0 for ch in text: if ch == "a" ch == "e": count 1 print(count)
or and not += -= ==
2
一個字母是 a 或是 e 都要計數,所以用 or。後面會學更簡潔的 in。
新工具小教學

先懂寫法,再做題

新工具 1

sum() 加總、round() 四捨五入

sum() 把一組數字加起來;round(數字, 位數) 保留指定小數位。

scores = [80, 90, 70] total = sum(scores) # 240 avg = total / len(scores) # 80.0 bmi = round(70 / 1.75 ** 2, 1) print(bmi) # 22.9
與暖身題的關係:sum(scores) 就是把「total = 0 後逐個 total += score」縮寫成一行。
新工具 2

dict.get(key, 預設值)

字典裡有 key 就取出值;沒有時交回預設值,不會發生 KeyError。

count = {"A": 2} print(count["A"]) # 2 print(count.get("A", 0)) # 2,因為 A 存在 print(count.get("B", 0)) # 0,因為 B 不存在
計數常用寫法:count[v] = count.get(v, 0) + 1。第一次看到 v 從 0 加 1,後面再看到就從舊值繼續加。
新工具 3

.split() 切字串、in 檢查是否在裡面

text = "banana milkshake" words = text.split() print(words) # ['banana', 'milkshake'] vowels = "aeiou" for ch in text: if ch in vowels: print(ch)
.split() 沒放參數時,會用空白切成 list。ch in vowels 是問「這個字元有沒有出現在 vowels 裡」。
新工具 4

一行判斷,與容器的真假

這兩種都是簡寫。看不懂時,先還原成第 2 章的 if/else 就好。

# 一行判斷:「成立的值 if 條件 else 不成立的值」 status = "及格" if avg >= 60 else "不及格" # 空 list 是 False;裡面有東西就是 True failed = ["數學"] if failed: print("有科目要補考")
if failed: 在這裡等同於 if len(failed) > 0:。這是 Python 常見寫法,不是新的判斷邏輯。
★★ 應用組

應用新舊工具:8 題

第 1 題★★

點餐結帳(滿額打折)

用到:dict 查價 · for 累加 · if 判斷 · f-string

點滿 200 元就打九折。

menu = {"漢堡": 80, "薯條": 45, "可樂": 30} order = ["漢堡", "可樂", "薯條", "漢堡"] total = 0 for item in : total += menu[] if total 200: total *= print(f"總共 {total} 元")
order menu item total >= > == 0.9 0.1
總共 211.5 元
for item in order 拿到的是「菜名」,再用 menu[item] 去查價錢。
「打九折」是乘以 0.9,不是減 0.1。
第 2 題★★

購物車扣庫存

用到:dict · for · if · continue · -=

庫存 0 的商品要跳過,不能扣成負的。

stock = {"筆記本": 3, "橡皮擦": 0, "原子筆": 10} cart = ["筆記本", "橡皮擦", "原子筆"] for item in cart: if == 0: print(f"{item} 缺貨") stock[item] 1 print(f"買了 {item},剩 {stock[item]}")
stock[item] stock cart[item] continue break pass -= += =
買了 筆記本,剩 2 橡皮擦 缺貨 買了 原子筆,剩 9
continue = 這一圈剩下的不做了,直接換下一個商品。
用 break 的話遇到缺貨就整個停掉,後面的原子筆就買不到了。
第 3 題★★

成績單:算平均 + 標及格

用到:函式 · dict · for · 新工具 sum() 與一行判斷

def average(nums): return (nums) len(nums) students = {"小明": [80, 90, 70], "小華": [50, 60, 40]} for name, scores in students.(): avg = average(scores) status = "及格" if avg >= 60 "不及格" print(f"{name}:{avg} 分 {status}")
sum len max / // % items keys values else elif
小明:80.0 分 及格 小華:50.0 分 不及格
平均 = 總和 / 個數,用 // 會把小數砍掉。
要同時拿名字和分數 → .items()。三元寫法是 A if 條件 else B。
第 4 題★★

統計及格人數與最高分

用到:list of dict · for · if · 計數 · f-string

records = [ {"name": "小明", "score": 92}, {"name": "小華", "score": 55}, {"name": "小美", "score": 78}, ] pass_count = 0 top = records[] for r in : if r["score"] >= 60: pass_count 1 if r["score"] > top[]: top = r print(f"及格 {pass_count} 人,最高分 {top['name']}")
0 1 -1 records r += == "score" "name" score
及格 2 人,最高分 小明
top 先設成第一筆 records[0],再逐筆比。
top["score"] 要用引號(key 是字串);寫 top[score] 會把 score 當變數找不到。
第 5 題★★

ATM 提款:金額檢查

用到:while · input/int · if · or · continue · list

輸入 0 結束;金額要是 100 的倍數,且不能超過餘額。

balance = 1000 history = [] while True: amount = int(input("金額(0 結束):")) if amount 0: break if amount % 100 0 amount > balance: print("金額不符或餘額不足") balance -= amount history.(amount) print(f"提款 {amount},餘 {balance}") print("紀錄:", history)
== = != % or and continue break append pop
提款 300,餘 700 金額不符或餘額不足 金額不符或餘額不足 紀錄: [300]
「不是 100 的倍數」或「超過餘額」,兩者只要中一個就退件 → 用 or。
用 and 的話要兩個都成立才擋,250 元就會被放行。
第 6 題★★

投票計票並找出當選人

用到:list · dict · 新工具 .get() · for · if 找最大

votes = ["A", "B", "A", "C", "A", "B"] count = {} for v in votes: count[v] = count.(v, 0) + 1 winner = "" best = 0 for name, n in count.(): if n best: best = n winner = print(count) print(f"當選:{winner}({best} 票)")
get keys pop items values > >= < name n
{'A': 3, 'B': 2, 'C': 1} 當選:A(3 票)
count.get(v, 0) = 這個 key 有就拿舊值,沒有就當 0 —— 省掉「第一次要先設 0」。
直接寫 count[v] 在第一次遇到新候選人時會 KeyError。
第 7 題★★

算字數與母音數

用到:字串 · 新工具 .split() / in · for 遍歷字元 · 計數

text = "banana milkshake" vowels = "aeiou" vcount = 0 words = text.() for ch in text: if ch vowels: vcount 1 print(f"{len()} 個字,{vcount} 個母音")
split strip join in is == += = words text
2 個字,6 個母音
text.split() 用空白切成單字清單,len(words) 就是字數。
ch in vowels 問「這個字母有沒有在母音字串裡」。
第 8 題★★

BMI 批次分級

用到:函式 · if/elif/else · tuple 拆解 · ** · 新工具 round()

def level(bmi): if bmi < 18.5: return "過輕" bmi < 24: return "正常" : return "過重" people = [("小明", 70, 1.75), ("小華", 45, 1.60)] for name, kg, m in : bmi = round(kg / m 2, 1) print(f"{name}:{bmi} {level(bmi)}")
elif if else people name ** * //
小明:22.9 正常 小華:17.6 過輕
第二段條件要「前面沒中才檢查」→ elif;最後的 else 不帶條件。
「m 的平方」是 m ** 2,m * 2 是乘以 2。
★★★ 選做挑戰組

選做挑戰:6 題

第 9 題★★★

待辦清單:新增與完成

用到:函式改 list · list of dict · for · if · bool · 新工具一行判斷

todos = [] def add(title): todos.({"title": title, "done": False}) def finish(title): for t in todos: if t["title"] title: t["done"] = add("買菜") add("寫作業") finish("買菜") for t in todos: mark = "v" if t[] else " " print(f"[{mark}] {t['title']}")
append add insert == = in True False "done" "title"
[v] 買菜 [ ] 寫作業
finish() 裡面是「比對」名字,用 ==;= 是賦值會直接壞掉。
完成就把 done 設成 True,顯示時再看 t["done"] 決定打不打勾。
第 10 題★★★

賓果卡:數完成幾條橫線

用到:巢狀 list · 巢狀 for · bool 旗標 · break · 計數

1 代表已劃記,一整列都是 1 就算一條線。

card = [ [1, 1, 1], [1, 0, 1], [0, 1, 1], ] lines = 0 for row in card: full = True for cell in : if cell 0: full = False if full: lines 1 print(f"完成 {lines} 條橫線")
row card cell == != break continue += =
完成 1 條橫線
內層迴圈走「這一列的每一格」→ for cell in row。
只要碰到一個 0,這列就不可能完成,full = False 之後 break 不用再看下去。
第 11 題★★★

多人點餐 + 服務費

用到:巢狀 dict/list · 函式 · for 累加 · round()

menu = {"牛排": 320, "沙拉": 120, "紅茶": 60} orders = {"小明": ["牛排", "紅茶"], "小華": ["沙拉", "紅茶"]} def bill(items): total = 0 for item in : total menu[] total grand = 0 for name, items in orders.(): subtotal = bill(items) grand subtotal print(f"{name}:{subtotal} 元") service = round(grand * , 1) print(f"小計 {grand},服務費 {service},共 {grand + service} 元")
item menu items items keys values += += -= return print 0.1 0.9
小明:380 元 小華:180 元 小計 560,服務費 56.0,共 616.0 元
bill() 刻意使用前 5 章學過的 for 累加:逐個用 menu[item] 查價。
函式內的 total 用 return 交回小計;服務費是小計的 10%,所以乘以 0.1。
第 12 題★★★

成績單:列出要補考的科目

用到:巢狀 dict · 巢狀 for · if/else · list append · 新工具容器真假

students = { "小明": {"國文": 80, "數學": 55, "英文": 90}, "小華": {"國文": 50, "數學": 45, "英文": 60}, } for name, subjects in students.items(): failed = [] for subject, score in subjects.(): if score 60: failed.(subject) if failed: print(f"{name} 要補考:{failed}") : print(f"{name} 全部及格")
items keys values < > <= append remove else elif
小明 要補考:['數學'] 小華 要補考:['國文', '數學']
外層跑「每個學生」,內層跑「這個學生的每一科」,各要 .items()。
if failed: 空清單當 False,所以有補考科目才會進第一個分支。
第 13 題★★★

多帳戶轉帳

用到:dict · 函式 · if 提早 return · -= / +=

accounts = {"1001": 5000, "1002": 800} def transfer(src, dst, amount): if accounts[src] amount: return "餘額不足" accounts[src] amount accounts[dst] amount return "轉帳成功" print(transfer("1001", "1002", 2000)) print(transfer("1002", "1001", 5000)) print(accounts[])
< > <= -= += = "1001" "1002" 1001
轉帳成功 餘額不足 3000
餘額「小於」要轉的金額就轉不成 → <,而且直接 return 結束,後面不會執行。
轉出帳戶 -=、轉入帳戶 +=,別放反。
第 14 題★★★

詞頻統計:找最常出現的字

用到:新工具 .split() / .get() · dict · for · if 找最大

text = "the cat the dog the cat cat" freq = {} for word in text.(): freq[word] = freq.(word, ) + 1 top_word = "" top_n = 0 for word, n in freq.items(): if n top_n: top_n = n top_word = word print(freq) print(f"最常出現:{top_word}({top_n} 次)")
split strip join get pop keys 0 1 > >=
{'the': 3, 'cat': 3, 'dog': 1} 最常出現:the(3 次)
freq.get(word, 0) 的第二個參數是「找不到時的預設值」,第一次遇到某個字就從 0 開始 +1。
用 >(嚴格大於)時,平手的 cat 不會頂掉先出現的 the。

進階題庫完成!

完成 0 / 18 題

這些題目拖對了,代表你看得懂跨章節的程式。
下一步:挑 2~3 題到 Playground,把整段從空白打出來,那才是真的會寫。

已完成 0 / 18 題