iT邦幫忙

2025 iThome 鐵人賽

DAY 28
0

前面複習了這麼多天,現在終於要把所學內容實際派上用場,真正進入專案實作了!
今天的目標是完成一個簡易「記帳系統」
功能:
1.新增一筆記帳資料(例如:日期、項目、金額)
2.查看所有紀錄
3.計算總支出 / 收入
4.離開系統
所有資料存進一個 .txt 或 .csv 檔案,程式重新啟動仍能看到紀錄
讓使用者輸入錯誤時可以提示並重新輸入(加上 try/except)

1.讀檔函式 load_records()
https://ithelp.ithome.com.tw/upload/images/20251012/20178872tcfMdSRYaw.png

  • 首先匯入 Python 內建的 os 模組,來檢查「檔案是否存在」
  • FILE_NAME = "expenses.txt" : 這是設定檔案名稱,所有的記帳資料都會存進這個檔案
  • records = []:建立一個空的列表,裡面會放多筆紀錄(每筆是 dict)
  • if os.path.exists(FILE_NAME)::檔案存在才進去讀,避免 FileNotFoundError
  • with 是上下文管理器,確保檔案使用完會自動關閉,"r" 表示讀取模式(read),encoding="utf-8" 保證中文能正確讀取(避免亂碼)
  • for line in f::逐行讀檔,每一行代表一筆紀錄(存在檔案裡)
  • line = line.strip():去掉行尾的換行符號 \n 與首尾空白,避免空白影響 split()
  • if line::如果該行不是空(排除空行)
  • date, item, amount = line.split(","):以逗號分割成三個欄位
  • records.append({...}):把解析好的字典加入 records
  • amount = int(amount):把金額由字串轉成整數,讓程式執行後可以加總與計算
  • return records:回傳整個列表給呼叫的程式
  • 如果 expenses.txt 裡有錯誤格式(例如某一行沒有三個欄位),split() 會失敗導致程式出錯,可用try/except 處理

2.存檔函式 save_records(records)
https://ithelp.ithome.com.tw/upload/images/20251012/20178872WceeHI74VM.png

  • "w" 為覆蓋寫入模式(write),每次會把原檔案清空再寫,如果想要追加(不覆蓋),可以改成 "a"(append),不過使用 append 要注意重複寫入或刪除時的管理
  • for r in records::把記憶中的每筆資料寫回檔案
  • f.write(f"{r['date']},{r['item']},{r['amount']}\n"):每筆寫一行,欄位用逗號分隔,最後加換行

3.新增記帳 add_record(records)
https://ithelp.ithome.com.tw/upload/images/20251012/20178872Y7r58hjfJl.png

  • date = input(...) / item = input(...):使用者輸入日期與項目
  • try: amount = int(input(...)):把金額字串轉整數
  • except ValueError: 捕捉非數字輸入,例如使用者輸入 abc,就會印錯誤訊息並 return(結束這個函式,不新增資料)
  • records.append(...):把新記錄放到列表裡(記憶體中)
  • save_records(records):立即把整個 records 寫回檔案,確保不會因為程式崩潰而丟失資料

4.查看紀錄 view_records(records)
https://ithelp.ithome.com.tw/upload/images/20251012/20178872Z1ZB6ip5G2.png

  • if not records::如果 records 是空列表,就告訴使用者沒有紀錄並 return
  • for r in records::逐筆印出紀錄
  • len(records):計算總筆數給使用者

5.計算總金額 total_amount(records)
https://ithelp.ithome.com.tw/upload/images/20251012/20178872iMB7AlDWjc.png

  • sum():把 records 裡每筆的 amount 相加

6.主程式(互動選單)
https://ithelp.ithome.com.tw/upload/images/20251012/20178872kqN6FbLwc8.png

  • records = load_records():開機就把舊資料放進 records
  • while True::無限迴圈,直到遇到 break(也就是使用者選 4)
  • choice = input(...):讀使用者選項(字串)
  • if/elif/else:根據輸入做不同事,注意:choice 是字串,比較 "1"、"2",不是整數 1

https://ithelp.ithome.com.tw/upload/images/20251012/20178872EZwTJcDxCh.png

  • 這是 Python 程式常見的入口寫法
  • name 等於 "main",會呼叫 main()

最後結果會輸出
1.新增記帳
https://ithelp.ithome.com.tw/upload/images/20251012/201788725QlA2680wj.png
https://ithelp.ithome.com.tw/upload/images/20251012/20178872rSNuHDlk6a.png
https://ithelp.ithome.com.tw/upload/images/20251012/20178872Zrth4XoQuF.png
2.查看紀錄
https://ithelp.ithome.com.tw/upload/images/20251012/20178872vMfv42qbec.png
3.計算總金額
https://ithelp.ithome.com.tw/upload/images/20251012/20178872m4eAmj1Y1u.png
4.離開
https://ithelp.ithome.com.tw/upload/images/20251012/20178872stNRUlTbxg.png

今天利用專案應用了前面所學到的技能有:

  • input()、型態轉換
  • if/elif/else 判斷流程
  • while 迴圈
  • list / dict 儲存資料
  • 檔案讀寫 open()
  • 例外處理

上一篇
Day27 : 用 Pandas 也能畫圖!
下一篇
Day29 : 小專案2 - 猜數字遊戲(終極密碼)
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記29
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言