第一堂:變數、if/else、while → 猜數字遊戲
第二堂:list 清單、for 迴圈、def 函式 → 記帳機
這堂課要學兩個超實用工具:字典和檔案操作。
第一堂:變數、if/else、while → 猜數字遊戲
第二堂:list 清單、for 迴圈、def 函式 → 記帳機
這堂課要學兩個超實用工具:字典和檔案操作。
字典(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}")
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!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" 追加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 物件永久保存到檔案!字典的強大應用場景:
# 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["一年一班"]["導師"]) # 王老師
# 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)) # 只取代第一次