← 課程總覽

📖 第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 物件永久保存到檔案!

🧪 小測驗:你學會了嗎?

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堂課