menu = {"漢堡": 80, "薯條": 45, "可樂": 30}
order = ["漢堡", "可樂", "薯條", "漢堡"]
total = 0
for item in :
total += menu[]
if total 200:
total *=
print(f"總共 {total} 元")
ordermenuitemtotal>=>==0.90.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]}")
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}")
sumlenmax///%itemskeysvalueselseelif
小明: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']}")
01-1recordsr+==="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)
===!=%orandcontinuebreakappendpop
提款 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} 票)")
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']}")
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} 條橫線")
rowcardcell==!=breakcontinue+==
完成 1 條橫線
內層迴圈走「這一列的每一格」→ for cell in row。
只要碰到一個 0,這列就不可能完成,full = False 之後 break 不用再看下去。
第 11 題★★★
多人點餐 + 服務費
用到:巢狀 dict/list · 函式 · for · sum() · round
menu = {"牛排": 320, "沙拉": 120, "紅茶": 60}
orders = {"小明": ["牛排", "紅茶"], "小華": ["沙拉", "紅茶"]}
def bill(items):
return sum(menu[] for i in items)
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} 元")
iitemmenuitemskeysvalues+=-=0.10.9
小明:380 元
小華:180 元
小計 560,服務費 56.0,共 616.0 元
sum(menu[i] for i in items) = 把這個人點的每樣東西的價錢加起來。
服務費是「小計的 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} 全部及格")
itemskeysvalues<><=appendremoveelseelif
小明 要補考:['數學']
小華 要補考:['國文', '數學']
外層跑「每個學生」,內層跑「這個學生的每一科」,各要 .items()。 if failed: 空清單當 False,所以有補考科目才會進第一個分支。
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} 次)")