第一堂:變數、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 物件永久保存到檔案!