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 題
會用到前 5 章與剛才的新工具,邏輯仍以直線流程為主
第 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} 元")
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} 票)")
用到:函式改 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']}")
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 累加 · 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} 元")
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} 次)")