当前位置: 首页 > news >正文

综合项目实践:基于基础语法核心的Python项目

        我们在第二阶段,已经学习了变量与数据类型、流程控制、数据结构,我为您设计了三个综合性项目。这些项目将帮助您巩固所学知识,并体验真实的编程场景。我建议您根据需求和设计思路先敲一遍,在看我给的代码。如果实在没有思路,我也做了简单的流程图,你可以照着流程图试试。最后一篇个人日记系统,没有看懂得话也不用担心,我会在后面写几篇关于这个日记管理系统的文章,我们逐步去扩展它可以添加的东西,完善它。

项目1:学生成绩管理系统

需求分析

创建一个命令行程序,能够:

  1. 添加学生信息(姓名、学号、成绩)

  2. 查看所有学生信息

  3. 计算全班平均分

  4. 查找特定学生信息

  5. 根据成绩排序学生

设计思路

  1. 使用字典存储单个学生信息,列表存储所有学生

  2. 使用while循环实现主菜单系统

  3. 使用条件语句处理用户选择

  4. 使用列表方法进行排序和查找操作

代码实现

系统流程图(文字描述版)

  • 主菜单循环
   ┌───────────────────────┐│     显示主菜单         ││ 1.添加 2.查看         ││ 3.平均分 4.查找       ││ 5.排序 6.退出         │└──────────┬────────────┘│┌──────────▼────────────┐│ 用户输入选择(1-6)      │└──────────┬────────────┘┌──────────┴────────────┐│ 根据选择调用对应功能模块 │└──────────┬────────────┘│┌──────────▼────────────┐│ 执行完成后返回主菜单   │└───────────────────────┘
  • 各功能模块流程

    添加学生

   ┌───────────────────────┐│ 输入姓名、学号、成绩    │├───────────────────────┤│ 检查学号是否重复       │├───────────────────────┤│ 创建学生字典并加入列表  │└───────────────────────┘

        查看学生

   ┌───────────────────────┐│ 检查列表是否为空       │├──────────┬────────────┤│ 是       │ 否         ││ 提示无数据│ 遍历打印   │└──────────┴────────────┘

        计算平均分

   ┌───────────────────────┐│ 检查列表是否为空       │├──────────┬────────────┤│ 是       │ 否         ││ 提示无数据│ 计算平均值 │└──────────┴────────────┘

代码1:

# 学生成绩管理系统
students = []def add_student():"""添加学生信息"""name = input("请输入学生姓名: ")student_id = input("请输入学号: ")score = float(input("请输入成绩: "))student = {"name": name,"id": student_id,"score": score}students.append(student)print(f"成功添加学生: {name}")def show_all_students():"""显示所有学生信息"""if not students:print("暂无学生信息")returnprint("\n所有学生信息:")print("-" * 30)for i, student in enumerate(students, 1):print(f"{i}. 姓名: {student['name']}, 学号: {student['id']}, 成绩: {student['score']}")def calculate_average():"""计算平均分"""if not students:print("暂无学生信息")returntotal = sum(student["score"] for student in students)average = total / len(students)print(f"全班平均分: {average:.2f}")def find_student():"""查找学生"""name = input("请输入要查找的学生姓名: ")found = Falsefor student in students:if student["name"] == name:print(f"找到学生: 姓名: {student['name']}, 学号: {student['id']}, 成绩: {student['score']}")found = Trueif not found:print("未找到该学生")def sort_students():"""按成绩排序学生"""global students#在 Python 中,如果在函数内部先使用了变量再声明 global,就会导致这个语法错误。#所有要先声明global,再在内部使用变量if not students:print("暂无学生信息")return# 使用sorted函数和lambda表达式按成绩降序排序students = sorted(students, key=lambda x: x["score"], reverse=True)print("已按成绩从高到低排序")def main_menu():"""主菜单"""while True:print("\n=== 学生成绩管理系统 ===")print("1. 添加学生")print("2. 查看所有学生")print("3. 计算平均分")print("4. 查找学生")print("5. 按成绩排序")print("6. 退出系统")choice = input("请选择操作 (1-6): ")if choice == "1":add_student()elif choice == "2":show_all_students()elif choice == "3":calculate_average()elif choice == "4":find_student()elif choice == "5":sort_students()elif choice == "6":print("感谢使用学生成绩管理系统!")breakelse:print("无效选择,请重新输入")# 启动系统
main_menu()

代码二:

class StudentManagementSystem:def __init__(self):self.students = []  # 初始化学生列表def add_student(self):"""添加学生信息"""name = input("请输入学生姓名: ").strip()student_id = input("请输入学号: ").strip()try:score = float(input("请输入成绩: "))if score < 0 or score > 100:raise ValueError("成绩必须在0-100之间")except ValueError as e:print(f"输入错误: {e}")return# 检查学号是否重复if any(s["id"] == student_id for s in self.students):print("该学号已存在!")returnstudent = {"name": name,"id": student_id,"score": score}self.students.append(student)print(f"成功添加学生: {name}")def show_all_students(self):"""显示所有学生信息"""if not self.students:print("暂无学生信息")returnprint("\n所有学生信息:")print("-" * 30)for i, student in enumerate(self.students, 1):print(f"{i}. 姓名: {student['name']}, 学号: {student['id']}, 成绩: {student['score']}")def calculate_average(self):"""计算平均分"""if not self.students:print("暂无学生信息")returntotal = sum(student["score"] for student in self.students)average = total / len(self.students)print(f"全班平均分: {average:.2f}")def find_student(self):"""查找学生"""name = input("请输入要查找的学生姓名: ").strip()if not name:print("请输入有效的姓名")returnfound_students = [s for s in self.students if name.lower() in s["name"].lower()]if not found_students:print("未找到该学生")returnprint("\n找到的学生信息:")print("-" * 30)for i, student in enumerate(found_students, 1):print(f"{i}. 姓名: {student['name']}, 学号: {student['id']}, 成绩: {student['score']}")def sort_students(self):"""按成绩排序学生"""if not self.students:print("暂无学生信息")returnself.students.sort(key=lambda x: x["score"], reverse=True)print("已按成绩从高到低排序")self.show_all_students()  # 显示排序后的结果def run(self):"""运行系统"""while True:print("\n=== 学生成绩管理系统 ===")print("1. 添加学生")print("2. 查看所有学生")print("3. 计算平均分")print("4. 查找学生")print("5. 按成绩排序")print("6. 退出系统")choice = input("请选择操作 (1-6): ").strip()if choice == "1":self.add_student()elif choice == "2":self.show_all_students()elif choice == "3":self.calculate_average()elif choice == "4":self.find_student()elif choice == "5":self.sort_students()elif choice == "6":print("感谢使用学生成绩管理系统!")breakelse:print("无效选择,请重新输入")if __name__ == "__main__":system = StudentManagementSystem()system.run()

代码三:

设计流程:

# 数据结构
students = []  # 全局列表,存储所有学生字典def main():while True:# 显示菜单print("1.添加 2.查看 3.平均分 4.查找 5.排序 6.退出")choice = input("请选择: ")if choice == "1":# 添加学生流程name = input("姓名: ")stu_id = input("学号: ")score = float(input("成绩: "))students.append({"name":name, "id":stu_id, "score":score})elif choice == "2":# 显示所有学生if not students:print("暂无数据")else:for stu in students:print(f"姓名:{stu['name']}, 成绩:{stu['score']}")elif choice == "3":# 计算平均分if students:avg = sum(s['score'] for s in students) / len(students)print(f"平均分: {avg:.2f}")# ... 其他功能类似elif choice == "6":breakif __name__ == "__main__":main()

以上代码的运行结果:


项目2:简易计算器

需求分析

创建一个命令行计算器,能够:

  1. 执行基本算术运算(加、减、乘、除)

  2. 支持连续计算

  3. 显示计算历史

  4. 清除当前计算

设计思路

  1. 使用变量存储当前结果和计算历史

  2. 使用字典映射运算符到对应的运算函数

  3. 使用while循环实现连续计算

  4. 使用列表存储计算历史

代码实现

代码一:

1. 系统流程图(分层架构)

2. 核心计算流程图

# 简易计算器
def add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(a, b):if b == 0:return "错误:除数不能为零"return a / b# 运算符映射字典
operations = {"+": add,"-": subtract,"*": multiply,"/": divide
}def calculator():"""计算器主函数"""history = []  # 存储计算历史result = 0    # 当前结果print("欢迎使用简易计算器!")print("支持的操作: +, -, *, /")print("输入 'c' 清除, 'h' 查看历史, 'q' 退出")while True:# 显示当前结果print(f"\n当前结果: {result}")# 获取运算符op = input("请输入运算符 (+, -, *, /) 或命令: ")if op == 'q':print("感谢使用计算器!")breakelif op == 'c':result = 0history = []print("已清除")continueelif op == 'h':if not history:print("暂无计算历史")else:print("计算历史:")for calc in history:print(calc)continueelif op not in operations:print("无效运算符")continue# 获取第二个操作数try:num = float(input("请输入数字: "))except ValueError:print("无效数字")continue# 执行计算if result == 0 and not history:# 第一次计算prev_num = float(input("请输入第一个数字: "))calculation = f"{prev_num} {op} {num}"result = operations[op](prev_num, num)calculation += f" = {result}"else:# 连续计算calculation = f"{result} {op} {num}"result = operations[op](result, num)calculation += f" = {result}"# 添加到历史history.append(calculation)print(calculation)# 启动计算器
calculator()

代码二:

1. 主程序流程图

2. 计算模块流程图

# 简易计算器
import math# 计算历史记录
calculation_history = []
current_result = 0# 运算函数映射
operations = {'+': lambda x, y: x + y,'-': lambda x, y: x - y,'*': lambda x, y: x * y,'/': lambda x, y: x / y if y != 0 else float('nan'),'^': lambda x, y: x ** y,'√': lambda x, y: x ** (1/y) if y != 0 and x >= 0 else float('nan')
}def add_to_history(expression, result):"""添加计算记录到历史"""calculation_history.append(f"{expression} = {result}")def show_history():"""显示计算历史"""if not calculation_history:print("暂无计算历史")returnprint("\n计算历史:")print("-" * 30)for i, record in enumerate(calculation_history, 1):print(f"{i}. {record}")def clear_history():"""清除计算历史"""global calculation_historycalculation_history = []print("计算历史已清除")def perform_calculation():"""执行计算"""global current_result# 显示当前结果print(f"\n当前结果: {current_result}")# 获取运算符print("可用运算符: +, -, *, /, ^ (幂), √ (开方)")operator = input("请输入运算符 (或输入 'c' 清除当前结果, 'h' 查看历史, 'q' 退出): ").strip()if operator.lower() == 'q':return 'quit'elif operator.lower() == 'h':show_history()return 'continue'elif operator.lower() == 'c':current_result = 0print("当前结果已清除")return 'continue'elif operator not in operations:print("无效的运算符")return 'continue'# 获取操作数try:if operator == '√':# 开方运算只需要一个操作数operand = float(input("请输入开方次数 (如 2 表示开平方): "))expression = f"√{current_result}({operand})"else:operand = float(input("请输入操作数: "))expression = f"{current_result} {operator} {operand}"# 执行计算result = operations[operator](current_result, operand)# 检查计算结果是否有效if math.isnan(result):print("错误: 无效的计算 (如除以零或负数开偶次方)")return 'continue'# 更新当前结果并添加到历史print(f"{expression} = {result}")add_to_history(expression, result)current_result = resultexcept ValueError:print("错误: 请输入有效的数字")return 'continue'def main():"""计算器主程序"""global current_resultprint("欢迎使用简易计算器!")print("输入 'q' 退出, 'h' 查看历史, 'c' 清除当前结果")while True:try:# 获取初始输入或继续计算if current_result == 0:current_result = float(input("\n请输入数字: "))# 执行计算status = perform_calculation()if status == 'quit':breakexcept ValueError:print("错误: 请输入有效的数字")except KeyboardInterrupt:print("\n感谢使用计算器!")breakif __name__ == "__main__":main()

运行结果:


项目3:个人日记系统

需求分析

创建一个简单的命令行日记系统,能够:

  1. 添加新日记

  2. 查看所有日记列表

  3. 查看特定日记内容

  4. 按日期搜索日记

设计思路

  1. 使用字典存储单篇日记(标题、内容、日期)

  2. 使用列表存储所有日记

  3. 使用日期时间模块记录日记创建时间

  4. 使用字符串方法实现简单搜索功能

代码实现

1. 系统流程图(分层架构)

2. 核心功能流程图

# 个人日记系统
import datetimediaries = []def add_diary():"""添加新日记"""title = input("请输入日记标题: ")content = input("请输入日记内容: ")# 获取当前日期时间now = datetime.datetime.now()date_str = now.strftime("%Y-%m-%d %H:%M")diary = {"title": title,"content": content,"date": date_str}diaries.append(diary)print("日记添加成功!")def list_diaries():"""列出所有日记"""if not diaries:print("暂无日记")returnprint("\n所有日记:")print("-" * 40)for i, diary in enumerate(diaries, 1):print(f"{i}. [{diary['date']}] {diary['title']}")def view_diary():"""查看特定日记"""if not diaries:print("暂无日记")returnlist_diaries()try:index = int(input("请输入要查看的日记编号: ")) - 1if 0 <= index < len(diaries):diary = diaries[index]print("\n" + "=" * 40)print(f"标题: {diary['title']}")print(f"日期: {diary['date']}")print("-" * 40)print(diary['content'])print("=" * 40)else:print("无效编号")except ValueError:print("请输入有效数字")def search_diaries():"""搜索日记"""if not diaries:print("暂无日记")returnkeyword = input("请输入搜索关键词: ")found = Falsefor i, diary in enumerate(diaries, 1):if keyword.lower() in diary['title'].lower() or keyword.lower() in diary['content'].lower():print(f"{i}. [{diary['date']}] {diary['title']}")found = Trueif not found:print("未找到相关日记")def main_menu():"""主菜单"""while True:print("\n=== 个人日记系统 ===")print("1. 写新日记")print("2. 查看日记列表")print("3. 阅读日记")print("4. 搜索日记")print("5. 退出系统")choice = input("请选择操作 (1-5): ")if choice == "1":add_diary()elif choice == "2":list_diaries()elif choice == "3":view_diary()elif choice == "4":search_diaries()elif choice == "5":print("感谢使用个人日记系统!")breakelse:print("无效选择,请重新输入")# 启动系统
main_menu()

代码二:

1. 系统主流程(顶层视图)

2. 核心功能详细流程

写日记流程

查看日记流程

3. 类方法调用关系

4. 数据流示意图

关键流程说明

  1. 初始化阶段

    • 系统启动时自动加载 JSON 数据文件
    • 如果文件不存在则初始化空列表
  2. 数据持久化

   # 保存时序图sequenceDiagram用户->>+系统: 添加新日记系统->>+内存: 更新entries列表内存->>+文件: 自动触发_save_entries文件-->>-用户: 显示保存成功
  1. 异常处理流程
   ┌──────────────┐│ 用户输入编号  │└──────┬───────┘│┌──────▼───────┐│ 尝试转换为整数 │└──────┬───────┘│┌──────▼───────┐│ 检查范围有效性 │└──────┬───────┘│┌──────▼───────┐ 否│ 是否在有效范围内├───┐└──────┬───────┘    ││是          │┌──────▼───────┐    ││ 显示日记内容 │    │└──────┬───────┘    ││            │┌──────▼───────┐    ││ 返回主菜单   │◄────┘└──────────────┘
import datetime
import json
import os
from typing import List, Dictclass DiarySystem:def __init__(self, storage_file='diary_data.json'):"""初始化日记系统"""self.storage_file = storage_fileself.entries: List[Dict] = []self._load_entries()def _load_entries(self):"""从文件加载已有日记"""if os.path.exists(self.storage_file):with open(self.storage_file, 'r', encoding='utf-8') as f:self.entries = json.load(f)def _save_entries(self):"""保存日记到文件"""with open(self.storage_file, 'w', encoding='utf-8') as f:json.dump(self.entries, f, ensure_ascii=False, indent=2)def _get_formatted_date(self) -> str:"""获取格式化的当前日期时间"""return datetime.datetime.now().strftime("%Y-%m-%d %H:%M")def add_entry(self):"""添加新日记条目"""print("\n" + "="*30 + " 新建日记 " + "="*30)title = input("请输入标题: ").strip()while not title:print("标题不能为空!")title = input("请输入标题: ").strip()content = []print("请输入内容(空行结束):")while True:line = input().strip()if not line:breakcontent.append(line)if not content:print("内容不能为空!")returnentry = {"title": title,"content": "\n".join(content),"date": self._get_formatted_date()}self.entries.append(entry)self._save_entries()print("日记保存成功!")def list_entries(self, entries=None):"""显示日记列表(可指定特定列表)"""target_entries = entries or self.entriesif not target_entries:print("\n当前没有日记")returnprint("\n" + "="*30 + " 日记列表 " + "="*30)for idx, entry in enumerate(target_entries, 1):print(f"{idx}. [{entry['date']}] {entry['title']}")print("="*70)def view_entry(self):"""查看特定日记内容"""if not self.entries:print("\n当前没有日记")returnself.list_entries()try:entry_num = int(input("请输入要查看的日记编号: ")) - 1if 0 <= entry_num < len(self.entries):entry = self.entries[entry_num]print("\n" + "="*30 + " 日记详情 " + "="*30)print(f"标题: {entry['title']}")print(f"日期: {entry['date']}")print("-"*70)print(entry['content'])print("="*70)else:print("无效的日记编号")except ValueError:print("请输入有效的数字")def search_entries(self):"""搜索日记条目"""if not self.entries:print("\n当前没有日记")returnkeyword = input("请输入搜索关键词: ").lower()results = [entry for entry in self.entriesif (keyword in entry['title'].lower() or keyword in entry['content'].lower())]if results:print(f"\n找到 {len(results)} 条匹配结果:")self.list_entries(results)else:print("\n没有找到匹配的日记")def run(self):"""运行日记系统主界面"""while True:print("\n" + "="*30 + " 个人日记系统 " + "="*30)print("1. 写新日记")print("2. 日记列表")print("3. 查看日记")print("4. 搜索日记")print("5. 退出系统")print("="*70)choice = input("请选择操作 (1-5): ").strip()if choice == "1":self.add_entry()elif choice == "2":self.list_entries()elif choice == "3":self.view_entry()elif choice == "4":self.search_entries()elif choice == "5":print("\n感谢使用日记系统,再见!")breakelse:print("无效的选择,请重新输入")if __name__ == "__main__":diary_app = DiarySystem()diary_app.run()

扩展建议流程图

  1. 添加分类功能

  1. 密码保护流程
┌──────────────┐
│  启动系统     │
└──────┬───────┘│
┌──────▼───────┐
│ 密码验证     │
└──────┬───────┘│
┌──────▼───────┐ 否
│ 是否匹配     ├───┐
└──────┬───────┘    ││是          │
┌──────▼───────┐    │
│ 进入主系统   │    │
└──────┬───────┘    ││            │
┌──────▼───────┐    │
│ 拒绝访问     │◄────┘
└──────────────┘

扩展后完整代码:

import datetime
import json
import os
import hashlib
from typing import List, Dict, Optionalclass DiarySystem:def __init__(self, storage_file='diary_data.json'):"""初始化日记系统(新增密码保护)"""self.storage_file = storage_fileself.backup_file = f"{os.path.splitext(storage_file)[0]}_backup.json"self.entries: List[Dict] = []self.categories = ["生活", "工作", "学习", "感悟", "其他"]  # 预设分类self.password_hash = self._load_password()# 密码验证流程if self.password_hash and not self._verify_password():print("密码错误,无法访问日记系统")exit()self._load_entries()if not self.password_hash:self._setup_password()# -------------------------- 新增:密码安全功能 --------------------------def _load_password(self) -> Optional[str]:"""加载已保存的密码哈希"""try:with open('.diary_config', 'r') as f:return f.readline().strip()except FileNotFoundError:return Nonedef _setup_password(self):"""首次使用设置密码"""print("\n=== 设置访问密码 ===")while True:pwd1 = input("请设置密码: ")pwd2 = input("请确认密码: ")if pwd1 == pwd2 and len(pwd1) >= 4:self.password_hash = hashlib.sha256(pwd1.encode()).hexdigest()with open('.diary_config', 'w') as f:f.write(self.password_hash)print("密码设置成功!")breakelif len(pwd1) < 4:print("密码长度至少需要4位")else:print("两次输入不一致,请重新设置")def _verify_password(self) -> bool:"""验证密码"""print("\n=== 密码验证 ===")for _ in range(3):  # 最多3次尝试机会pwd = input("请输入访问密码: ")if hashlib.sha256(pwd.encode()).hexdigest() == self.password_hash:return Trueprint("密码错误,还有", 2 - _, "次机会")return False# -------------------------- 新增:数据备份功能 --------------------------def _backup_data(self):"""自动备份日记数据"""if os.path.exists(self.storage_file):with open(self.storage_file, 'r', encoding='utf-8') as f:data = f.read()with open(self.backup_file, 'w', encoding='utf-8') as f:f.write(data)print("✓ 数据已自动备份")def restore_backup(self):"""从备份恢复数据"""if os.path.exists(self.backup_file):confirm = input("确定要从备份恢复数据吗?(y/n): ").lower()if confirm == 'y':with open(self.backup_file, 'r', encoding='utf-8') as f:self.entries = json.load(f)self._save_entries()print("✓ 已从备份恢复数据")else:print("没有找到备份文件")# -------------------------- 原有功能优化 --------------------------def _load_entries(self):"""从文件加载已有日记"""if os.path.exists(self.storage_file):try:with open(self.storage_file, 'r', encoding='utf-8') as f:self.entries = json.load(f)except json.JSONDecodeError:print("警告:日记数据文件损坏,尝试从备份恢复...")self.restore_backup()else:self.entries = []def _save_entries(self):"""保存日记到文件(新增自动备份)"""with open(self.storage_file, 'w', encoding='utf-8') as f:json.dump(self.entries, f, ensure_ascii=False, indent=2)self._backup_data()  # 保存后自动备份# -------------------------- 新增:日记分类与天气 --------------------------def add_entry(self):"""添加新日记条目(新增分类和天气)"""print("\n" + "="*30 + " 新建日记 " + "="*30)title = input("请输入标题: ").strip()while not title:print("标题不能为空!")title = input("请输入标题: ").strip()# 新增:选择分类print("\n请选择分类:")for i, cat in enumerate(self.categories, 1):print(f"  {i}. {cat}")while True:try:cat_choice = int(input("分类编号 (1-5): ")) - 1if 0 <= cat_choice < len(self.categories):category = self.categories[cat_choice]breakprint("请输入1-5之间的数字")except ValueError:print("请输入有效的数字")# 新增:记录天气weather = input("\n请输入天气 (如:晴朗/多云): ").strip() or "未记录"# 正文内容content = []print("\n请输入日记内容(空行结束):")while True:line = input().rstrip('\n')  # 保留换行但去除输入时的额外空行if not line:breakcontent.append(line)if not content:print("内容不能为空!")returnentry = {"title": title,"content": "\n".join(content),"date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),"category": category,  # 新增字段"weather": weather     # 新增字段}self.entries.append(entry)self._save_entries()print("✓ 日记保存成功!")# -------------------------- 新增:日记修改与删除 --------------------------def manage_entries(self):"""管理日记(修改/删除功能)"""if not self.entries:print("\n当前没有日记")returnself.list_entries()try:entry_num = int(input("请输入要管理的日记编号: ")) - 1if 0 <= entry_num < len(self.entries):entry = self.entries[entry_num]print(f"\n标题: {entry['title']}")print(f"日期: {entry['date']}")print(f"分类: {entry['category']} | 天气: {entry['weather']}")print("-"*70)print(entry['content'])print("="*70)print("\n1. 修改日记  2. 删除日记  3. 返回")choice = input("请选择操作: ")if choice == "1":self._edit_entry(entry_num)elif choice == "2":self._delete_entry(entry_num)else:print("无效的日记编号")except ValueError:print("请输入有效的数字")def _edit_entry(self, index):"""修改日记"""entry = self.entries[index]print("\n" + "="*30 + " 修改日记 " + "="*30)new_title = input(f"标题 ({entry['title']}): ").strip()new_content = []print("\n当前内容(按Enter保留,输入新内容替换):")print("-"*70)print(entry['content'])print("-"*70)print("请输入新内容(空行结束):")while True:line = input().rstrip('\n')if not line:breaknew_content.append(line)# 只更新有输入的字段if new_title:entry['title'] = new_titleif new_content:entry['content'] = "\n".join(new_content)entry['last_modified'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")self._save_entries()print("✓ 日记修改成功!")def _delete_entry(self, index):"""删除日记"""entry = self.entries[index]confirm = input(f"确定要删除《{entry['title']}》吗?(y/n): ").lower()if confirm == 'y':del self.entries[index]self._save_entries()print("✓ 日记已删除")else:print("已取消删除")# -------------------------- 优化:分类筛选与搜索 --------------------------def filter_by_category(self):"""按分类筛选日记"""print("\n" + "="*30 + " 分类筛选 " + "="*30)for i, cat in enumerate(self.categories, 1):print(f"  {i}. {cat}")try:cat_choice = int(input("分类编号 (1-5): ")) - 1if 0 <= cat_choice < len(self.categories):filtered = [e for e in self.entries if e['category'] == self.categories[cat_choice]]print(f"\n--- {self.categories[cat_choice]} 分类日记 ---")self.list_entries(filtered)else:print("无效的分类编号")except ValueError:print("请输入有效的数字")# -------------------------- 优化:主菜单与交互 --------------------------def run(self):"""运行日记系统主界面(更新菜单)"""while True:print("\n" + "="*30 + " 个人日记系统 " + "="*30)print("1. 写新日记   2. 日记列表   3. 查看日记")print("4. 分类筛选   5. 搜索日记   6. 管理日记")print("7. 备份恢复   8. 退出系统")print("="*70)choice = input("请选择操作 (1-8): ").strip()if choice == "1":self.add_entry()elif choice == "2":self.list_entries()elif choice == "3":self.view_entry()elif choice == "4":self.filter_by_category()elif choice == "5":self.search_entries()elif choice == "6":self.manage_entries()elif choice == "7":self.restore_backup()elif choice == "8":print("\n感谢使用个人日记系统!")breakelse:print("无效的选择,请重新输入")if __name__ == "__main__":diary_app = DiarySystem()diary_app.run()


文章转载自:

http://V0HdNIAL.ksjnL.cn
http://yK4JI1ON.ksjnL.cn
http://z9I0GsjW.ksjnL.cn
http://9UJdquee.ksjnL.cn
http://uQCKSFEF.ksjnL.cn
http://h7Up7uSF.ksjnL.cn
http://ND6o12l3.ksjnL.cn
http://lYFUVgG9.ksjnL.cn
http://dqfrmoNp.ksjnL.cn
http://5Ml0zuir.ksjnL.cn
http://NNpePBa6.ksjnL.cn
http://C4roQAzs.ksjnL.cn
http://XBpneaf3.ksjnL.cn
http://x01SPZHN.ksjnL.cn
http://7khFheUm.ksjnL.cn
http://O92JbKI8.ksjnL.cn
http://rxcMGeNS.ksjnL.cn
http://A1MS1yax.ksjnL.cn
http://Lz4i7uYt.ksjnL.cn
http://kRgL2TK2.ksjnL.cn
http://rhQrlTBQ.ksjnL.cn
http://Hze7RWc2.ksjnL.cn
http://f6euatvQ.ksjnL.cn
http://K8acnGZU.ksjnL.cn
http://B1wNtuVX.ksjnL.cn
http://TDHBa9BY.ksjnL.cn
http://8EY5HeZZ.ksjnL.cn
http://TQQEmONC.ksjnL.cn
http://FLDjpIpz.ksjnL.cn
http://dpsb5D4u.ksjnL.cn
http://www.dtcms.com/a/378296.html

相关文章:

  • 开始 ComfyUI 的 AI 绘图之旅-Flux.1图生图(八)
  • 供应商管理系统包含哪些模块?
  • MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
  • Apache服务——搭建实验
  • “一半是火焰,一半是海水”,金融大模型的爆发与困局
  • 开源 C++ QT Widget 开发(十六)程序发布
  • MPC控制器C语言实现:基于一阶RL系统
  • C++版单例模式-现代化简洁写法
  • 强大的开源文档问答工具-Kotaemon
  • 音视频学习(六十三):AVCC和HVCC
  • 深度解析强化学习(RL):原理、算法与金融应用
  • 独立显卡和集成显卡切换电脑卡住了怎么办?
  • 加固笔记本是什么意思?加固笔记本图片
  • 光子精密3D线激光轮廓测量仪:赋能手机生产全流程质量与效率升级
  • springboot excel 表格入门与实战
  • react实现无缝轮播组件
  • DbGate数据库管理新方案:cpolar打造跨平台远程访问通道
  • Spark+Hive中间件
  • 【案例分享】TeeChart 助力 Softdrill 提升油气钻井数据可视化能力
  • 在图形 / 游戏开发中,为何 Pixels Per Unit(PPU)数值越小,物体在屏幕上显示的尺寸越大?
  • new和mallo的区别
  • mysql中%前置模糊查询怎么优化
  • 单串口服务器-工业级串口联网解决方案
  • 使用 Tkinter + Requests 实现地理信息安全系统学习时长助手
  • 多语言共享贩卖机投资理财共享售卖机投资理财系统
  • 京东JDS 测评图形规律题答题技巧
  • 打工人日报#20250911
  • 一、WPF入门介绍+Grid和StackPanel布局介绍+实战模拟Notepad++页面布局
  • 电商平台用户流失预测与干预机制
  • 华为网路设备学习-33(BGP协议 八)BGP路由 选路规则