寫程式最重要的是「能解決問題」。記事本是最貼近日常生活的應用之一,能幫我們記下代辦事項、靈感或學習筆記。
1.使用者可以選擇功能:
2.透過 while 迴圈持續運行,直到使用者選擇退出。
def add_note():
note = input("請輸入記事內容:")
with open("notes.txt", "a", encoding="utf-8") as f:
f.write(note + "\n")
print("已新增記事!")
def show_notes():
try:
with open("notes.txt", "r", encoding="utf-8") as f:
notes = f.readlines()
if notes:
print("所有記事:")
for i, note in enumerate(notes, 1):
print(f"{i}. {note.strip()}")
else:
print("沒有任何記事")
except FileNotFoundError:
print("尚未建立記事檔案")
def clear_notes():
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("")
print("已清除所有記事!")
while True:
print("\n=== 簡易記事本 ===")
print("1. 新增記事")
print("2. 查看記事")
print("3. 清除全部記事")
print("4. 離開")
choice = input("請選擇功能:")
if choice == "1":
add_note()
elif choice == "2":
show_notes()
elif choice == "3":
clear_notes()
elif choice == "4":
print("再見!")
break
else:
print("輸入錯誤,請重新選擇")
今日小挑戰
這個挑戰能讓你體驗如何把「資料」與「時間」結合,做出更貼近真實需求的工具。
--- by Ricky