← 課程總覽

📖 第3堂課:字典、字串與檔案

程式學習第三堂課:Python 字典 dict、字串處理、檔案讀寫、JSON 儲存、個人通訊錄專案
含語音講解(約 60 分鐘),附互動小測驗

📖 第一階段:字典與字串(約 25 分鐘)

1. 快速複習

⏱ 5 分鐘

第一堂:變數、if/else、while → 猜數字遊戲
第二堂:list 清單、for 迴圈、def 函式 → 記帳機

這堂課要學兩個超實用工具:字典檔案操作

2. 字典 dict:給資料貼標籤

⏱ 15 分鐘

字典(dict)用鍵(key)→ 值(value)的對應來存資料:

student = {"name": "丁丁","age": 25,"city": "台北"}
print(student["name"])  # 丁丁
print(student.get("phone", "無資料"))  # 安全取值

for key, value in student.items():
    print(f"{key}: {value}")
💡 list:順序重要、同類資料 | dict:標籤重要、異質資料

3. 字串處理

⏱ 10 分鐘
text = "  Hello, Python!  "
print(text.strip())          # "Hello, Python!"
print(text.replace("Python", "程式"))
print(text.split(","))       # ['  Hello', ' Python!  ']
print(",".join(["A","B"]))  # "A,B"
name = "丁丁"; score = 95
print(f"{name} 的成績是 {score} 分")  # f-string!

📖 第二階段:檔案讀寫(約 20 分鐘)

4. 檔案操作:讓資料永久保存

⏱ 15 分鐘
with open("diary.txt", "w", encoding="utf-8") as f:
    f.write("今天天氣很好!\n")

with open("diary.txt", "r", encoding="utf-8") as f:
    content = f.read()

with open("diary.txt", "a", encoding="utf-8") as f:
    f.write("追加一行!\n")  # 不覆蓋
📝 "r" 讀取 | "w" 寫入(覆蓋)| "a" 追加
一定要加 encoding="utf-8"

📖 第三階段:實戰(約 15 分鐘)

5. 專案:個人通訊錄

⏱ 10 分鐘
import json

def load_contacts():
    try:
        with open("contacts.json", "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_contacts(contacts):
    with open("contacts.json", "w", encoding="utf-8") as f:
        json.dump(contacts, f, ensure_ascii=False, indent=2)

contacts = load_contacts()
contacts.append({"name": "丁丁", "phone": "0912-345-678"})
save_contacts(contacts)
json 模組讓 Python 物件永久保存到檔案!

🔍 深入字典:常見模式與陷阱

⏱ 10 分鐘

字典的強大應用場景:

# 1. 當作簡易資料庫 — 用 id 查資料
users = {1: "丁丁", 2: "拉拉", 3: "小波"}
print(users[2])  # 拉拉

# 2. 計數器 — 統計出現次數
text = "apple banana apple orange banana apple"
counter = {}
for word in text.split():
    counter[word] = counter.get(word, 0) + 1
print(counter)  # {'apple': 3, 'banana': 2, 'orange': 1}

# 3. 巢狀字典 — 多層資料
school = {
    "一年一班": {"導師": "王老師", "人數": 30},
    "一年二班": {"導師": "林老師", "人數": 28}
}
print(school["一年一班"]["導師"])  # 王老師
⚠️ 常見陷阱:dict key 必須是「不可變」型別(str、int、tuple),不能用 list 當 key!
🔑 dict 是 Python 3.7+ 保證有序 — 插入順序就是迭代順序。

🔍 深入字串:格式化與實用方法

⏱ 8 分鐘
# f-string 進階:運算式、格式化
price = 99.9
print(f"價格:{price} 元,含稅 {price * 1.05:.1f} 元")

# 字串常用判斷方法
s = "Python3.12"
print(s.startswith("Py"))    # True
print(s.isdigit())           # False
print("123".isdigit())       # True

# 字串搜尋與取代
text = "我喜歡Python,Python很有趣"
print(text.find("Python"))        # 3
print(text.count("Python"))       # 2
print(text.replace("Python", "程式設計", 1))  # 只取代第一次
💡 f-string 是 Python 3.6+ 最推薦的字串格式化方式,比 % 或 .format() 更快更易讀。

🧪 小測驗:你學會了嗎?

5 題選擇題,選完按「交卷」看成績
第 1 / 5 題
dict 中用來查資料的是什麼?
第 2 / 5 題
student.get("grade", "無"),grade 不存在時回傳?
第 3 / 5 題
寫入檔案不覆蓋原有內容用哪個模式?
第 4 / 5 題
json.dump() 的作用?
第 5 / 5 題
處理中文檔案 open() 一定要加?
你的得分
0/5

🎯 第3堂課,你學會了什麼?

dict 字典字串處理檔案讀寫JSON 儲存通訊錄專案

你現在可以讓程式「記住」資料了——從玩具程式邁向實用工具的重要一步!

→ 前往第4堂課