“是吗？”立浪咕哝了一句，再次陷入沉默，然后突然问我，“叶村君，你跟剑崎同学在交往吗？”我心里一惊。并不单纯因为我的名字跟比留子同学那样的美人被一同提了出来，同时也因为他突然说起了关于女性的话题。我回答：“没有，我们不是那种关系。”然而他的反应却让我感到有些意外：“她很喜欢你哦。”那个语气仿佛在谈论天气。“你说比留子同学？”怎么可能？“你跟女生交往过吗？”我很老实地摇了摇头，他露出微笑：“是吗？原来你们都是新手。那可是最美好的时光啊。”“对方可不一定是新手啊。”“这是我的直觉——不过极有可能命中。要是她真的接触过男人，肯定不会这么没有戒心。”我好像能明白他的意思，但还是想狡辩几句：“比留子同学可能只是性格直率，爱亲近人而已。”“确实，头一次看到她时，我也真心想追求。毕竟她脑子聪明，脸蛋漂亮，那种姿色可不常见啊。可我后来还是放弃了。因为她看起来深藏不露，其实单纯得很。跟那种女孩子相处很累人的，因为她们嗅不出一段关系的终结，非常棘手。”他竟会在女性方面示弱，让我感到十分意外：“不好意思……我还以为立浪前辈不是那种挑剔的人。”“单说经验的数量我倒是有很多，可那些都是让我恨不得遗忘的回忆。刚认识那段时间固然很快乐，只是越熟悉对方，就越疑惑我们是否真的互相喜欢，然后越来越难以相信对方。一旦分手了，更是觉得之前的一切都是欺瞒。”摘录来自尸人庄谜案[日]今村昌弘 著 吕灵芝 译此材料受版权保护。
阶段六：大师 (Level 51-60)目标：架构设计，性能极致优化，贡献开源任务清单：系统架构设计：分布式系统基础数据库优化：SQL优化，连接池缓存策略：Redis，内存管理消息队列：Celery，RabbitMQ安全编程：常见漏洞防范部署运维：Docker，监控开源贡献：为开源项目提交PR终极Boss战：项目：完整的SaaS应用用户认证系统数据分析和报表自动化部署性能监控特殊任务（支线任务）工具熟练度：Git版本控制数据库操作(SQLite/MySQL/PostgreSQL)正则表达式精通Linux环境熟练领域专精：Web开发：Django/Flask/FastAPI数据分析：Pandas, NumPy, Matplotlib机器学习：Scikit-learn, PyTorch/TensorFlow自动化运维：Ansible, 脚本编写升级检查点
阶段五：专家 (Level 41-50)目标：系统设计，性能优化，源码理解任务清单：设计模式：单例、工厂、观察者等高级异步：asyncio高级用法C扩展：Cython基础使用协议和抽象基类：鸭子类型深入描述符高级用法：自定义属性行为元类应用：框架级别开发源码阅读：阅读常用库源码小Boss战：项目：微型Web框架路由系统中间件机制ORM基础功能阶段六：大师 (Level 51-60)目标：架构设计，性能极致优化，贡献开源任务清单：系统架构设计：分布式系统基础数据库优化：SQL优化，连接池缓存策略：Redis，内存管理消息队列：Celery，RabbitMQ安全编程：常见漏洞防范部署运维：Docker，监控开源贡献：为开源项目提交PR
阶段四：勇士 (Level 31-40)目标：掌握并发编程，深入理解语言机制任务清单：多线程：threading模块，GIL理解多进程：multiprocessing模块异步编程：asyncio基础内存管理：引用计数，垃圾回收性能分析：cProfile, timeit使用代码规范：PEP8，代码质量工具单元测试：unittest/pytest小Boss战：项目：并发网络爬虫多线程爬取网页数据解析和存储速率限制和异常处理
阶段三：挑战者 (Level 21-30)目标：掌握高级特性，理解Pythonic编程任务清单：装饰器：理解并编写自己的装饰器生成器：yield关键字，惰性计算上下文管理器：with语句，资源管理迭代器协议：iter, next属性管理：@property, @setter描述符：理解属性访问机制元编程：type, metaclass基础小Boss战：项目：Web API客户端使用requests库调用API实现数据缓存装饰器异常处理和重试机制
阶段二：进阶者 (Level 11-20)目标：理解面向对象，掌握常用模块任务清单：面向对象：类、对象# 现实世界：狗 # 属性：名字、品种、年龄 # 行为：叫、跑、吃 # 在Python中定义类 class Dog: # 构造函数：创建对象时自动调用 def __init__(self, name, breed, age): # 属性（实例变量） self.name = name self.breed = breed self.age = age # 方法（行为） def bark(self): print(f"{self.name} 在汪汪叫！") def run(self): print(f"{self.name} 在奔跑...") def eat(self, food): print(f"{self.name} 正在吃 {food}") # 创建对象（实例化） my_dog = Dog("旺财", "金毛", 3) friend_dog = Dog("小黑", "拉布拉多", 2) # 使用对象 print(f"我的狗叫 {my_dog.name}，是 {my_dog.breed}，{my_dog.age} 岁") my_dog.bark() my_dog.eat("狗粮") print(f"朋友的狗叫 {friend_dog.name}") friend_dog.run()class Student: def __init__(self, name, student_id, grade): self.name = name self.student_id = student_id self.grade = grade self.scores = {} # 字典存储成绩 def add_score(self, subject, score): """添加科目成绩""" self.scores[subject] = score print(f"为 {self.name} 添加了 {subject} 成绩: {score}") def get_average_score(self): """计算平均分""" if not self.scores: return 0 return sum(self.scores.values()) / len(self.scores) def display_info(self): """显示学生信息""" print(f"学生: {self.name} (学号: {self.student_id})") print(f"班级: {self.grade}") if self.scores: print("成绩:") for subject, score in self.scores.items(): print(f" {subject}: {score}") print(f"平均分: {self.get_average_score():.2f}") else: print("暂无成绩") print("-" * 30) # 测试学生类 student1 = Student("小明", "2024001", "高三(1)班") student2 = Student("小红", "2024002", "高三(1)班") student1.add_score("数学", 95) student1.add_score("英语", 88) student2.add_score("数学", 92) student2.add_score("英语", 90) student1.display_info() student2.display_info()继承# 父类（基类） class Animal: def __init__(self, name, age): self.name = name self.age = age def eat(self): print(f"{self.name} 在吃东西") def sleep(self): print(f"{self.name} 在睡觉") def make_sound(self): print(f"{self.name} 发出声音") # 子类（派生类） class Dog(Animal): # 继承Animal类 def __init__(self, name, age, breed): super().__init__(name, age) # 调用父类的构造函数 self.breed = breed # 重写父类方法 def make_sound(self): print(f"{self.name} 在汪汪叫！") # 子类特有的方法 def fetch(self): print(f"{self.name} 在接飞盘") class Cat(Animal): def __init__(self, name, age, color): super().__init__(name, age) self.color = color def make_sound(self): print(f"{self.name} 在喵喵叫！") def climb_tree(self): print(f"{self.name} 在爬树") # 测试继承 dog = Dog("旺财", 3, "金毛") cat = Cat("咪咪", 2, "白色") print(f"{dog.name} 是 {dog.breed}") dog.eat() dog.make_sound() dog.fetch() print(f"\n{cat.name} 是 {cat.color}的") cat.sleep() cat.make_sound() cat.climb_tree()import math class Shape: """图形基类""" def __init__(self, name): self.name = name def area(self): """计算面积""" raise NotImplementedError("子类必须实现这个方法") def perimeter(self): """计算周长""" raise NotImplementedError("子类必须实现这个方法") def display_info(self): print(f"图形: {self.name}") print(f"面积: {self.area():.2f}") print(f"周长: {self.perimeter():.2f}") print("-" * 30) class Rectangle(Shape): """矩形类""" def __init__(self, width, height): super().__init__("矩形") self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) class Circle(Shape): """圆形类""" def __init__(self, radius): super().__init__("圆形") self.radius = radius def area(self): return math.pi * self.radius ** 2 def perimeter(self): return 2 * math.pi * self.radius class Triangle(Shape): """三角形类""" def __init__(self, a, b, c): super().__init__("三角形") self.a = a self.b = b self.c = c def area(self): # 使用海伦公式 s = self.perimeter() / 2 return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c)) def perimeter(self): return self.a + self.b + self.c # 测试图形类 shapes = [ Rectangle(5, 3), Circle(4), Triangle(3, 4, 5) ] for shape in shapes: shape.display_info()封装class BankAccount: def __init__(self, account_holder, initial_balance=0): self.account_holder = account_holder self._balance = initial_balance # 保护属性 self._transaction_history = [] # 交易记录 # 使用@property装饰器提供受控访问 @property def balance(self): return self._balance def deposit(self, amount): """存款""" if amount <= 0: print("存款金额必须大于0") return False self._balance += amount self._transaction_history.append(f"存款: +{amount}元") print(f"存款成功！当前余额: {self._balance}元") return True def withdraw(self, amount): """取款""" if amount <= 0: print("取款金额必须大于0") return False if amount > self._balance: print("余额不足！") return False self._balance -= amount self._transaction_history.append(f"取款: -{amount}元") print(f"取款成功！当前余额: {self._balance}元") return True def get_transaction_history(self): """获取交易记录""" return self._transaction_history.copy() # 返回副本保护原始数据 # 测试银行账户 account = BankAccount("张三", 1000) print(f"账户持有人: {account.account_holder}") account.deposit(500) account.withdraw(200) account.withdraw(2000) # 会失败 print("交易记录:", account.get_transaction_history())class Temperature: def __init__(self, celsius=0): self._celsius = celsius # 内部存储为摄氏度 @property def celsius(self): return self._celsius @celsius.setter def celsius(self, value): if value < -273.15: # 绝对零度 raise ValueError("温度不能低于绝对零度(-273.15°C)") self._celsius = value @property def fahrenheit(self): return (self._celsius * 9/5) + 32 @fahrenheit.setter def fahrenheit(self, value): self.celsius = (value - 32) * 5/9 @property def kelvin(self): return self._celsius + 273.15 @kelvin.setter def kelvin(self, value): if value < 0: raise ValueError("开尔文温度不能低于0") self.celsius = value - 273.15 def display(self): print(f"{self.celsius:.2f}°C = {self.fahrenheit:.2f}°F = {self.kelvin:.2f}K") # 测试温度类 temp = Temperature(25) temp.display() print("\n设置华氏温度:") temp.fahrenheit = 100 temp.display() print("\n设置开尔文温度:") temp.kelvin = 300 temp.display()多态和方法重写class Employee: """员工基类""" def __init__(self, name, salary): self.name = name self.salary = salary def work(self): print(f"{self.name} 在工作") def calculate_bonus(self): """计算奖金 - 基类实现""" return self.salary * 0.1 def get_info(self): return f"员工: {self.name}, 月薪: {self.salary}, 奖金: {self.calculate_bonus()}" class Manager(Employee): """经理类""" def __init__(self, name, salary, team_size): super().__init__(name, salary) self.team_size = team_size def work(self): print(f"{self.name} 经理在管理团队") def calculate_bonus(self): """重写奖金计算方法""" return self.salary * 0.2 + self.team_size * 100 def get_info(self): base_info = super().get_info() return f"{base_info}, 团队规模: {self.team_size}人" class Developer(Employee): """开发人员类""" def __init__(self, name, salary, programming_language): super().__init__(name, salary) self.programming_language = programming_language def work(self): print(f"{self.name} 在用 {self.programming_language} 编程") def calculate_bonus(self): """重写奖金计算方法""" bonus = self.salary * 0.15 if self.programming_language in ["Python", "Java"]: bonus += 500 # 热门语言额外奖金 return bonus def get_info(self): base_info = super().get_info() return f"{base_info}, 编程语言: {self.programming_language}" # 测试多态 employees = [ Manager("张总", 20000, 5), Developer("小李", 15000, "Python"), Developer("小王", 12000, "Java"), Employee("普通员工", 8000) ] print("=== 员工工作状态 ===") for employee in employees: employee.work() print("\n=== 员工信息 ===") for employee in employees: print(employee.get_info()) # 演示多态：同样的方法，不同的行为 print("\n=== 奖金计算（多态演示）===") total_bonus = 0 for employee in employees: bonus = employee.calculate_bonus() print(f"{employee.name} 的奖金: {bonus:.2f}元") total_bonus += bonus print(f"\n总奖金支出: {total_bonus:.2f}元")类方法 vs 静态方法 vs 实例方法class Student: # 类属性（所有对象共享） school_name = "阳光中学" total_students = 0 def __init__(self, name, grade): self.name = name # 实例属性 self.grade = grade Student.total_students += 1 # 更新类属性 # 实例方法 - 操作实例数据 def introduce(self): print(f"我是{self.name}，在{self.school_name}读{self.grade}") # 类方法 - 操作类数据，第一个参数是cls @classmethod def get_total_students(cls): return cls.total_students @classmethod def create_from_string(cls, student_string): """从字符串创建学生对象 - 类方法作为工厂方法""" name, grade = student_string.split(",") return cls(name.strip(), grade.strip()) @classmethod def change_school_name(cls, new_name): cls.school_name = new_name print(f"学校已更名为: {new_name}") # 静态方法 - 不操作类或实例数据 @staticmethod def is_valid_grade(grade): """验证年级格式""" valid_grades = ["初一", "初二", "初三", "高一", "高二", "高三"] return grade in valid_grades @staticmethod def calculate_grade_average(scores): """计算平均分""" if not scores: return 0 return sum(scores) / len(scores) # 测试各种方法 print("=== 实例方法测试 ===") student1 = Student("小明", "高三") student1.introduce() print("\n=== 类方法测试 ===") print(f"总学生数: {Student.get_total_students()}") # 使用类方法创建对象 student2 = Student.create_from_string("小红, 高二") student2.introduce() Student.change_school_name("希望中学") student1.introduce() # 所有对象都会受到影响 student2.introduce() print("\n=== 静态方法测试 ===") print(f"'{student1.grade}' 是有效年级: {Student.is_valid_grade(student1.grade)}") print(f"'{大学}' 是有效年级: {Student.is_valid_grade('大学')}") scores = [85, 92, 78, 96, 88] print(f"成绩平均分: {Student.calculate_grade_average(scores):.2f}") print(f"\n当前总学生数: {Student.get_total_students()}")小结class Book: """图书类""" total_books = 0 def __init__(self, title, author, isbn, total_copies=1): self.title = title self.author = author self.isbn = isbn self.total_copies = total_copies self.available_copies = total_copies Book.total_books += 1 def borrow(self): """借书""" if self.available_copies > 0: self.available_copies -= 1 return True return False def return_book(self): """还书""" if self.available_copies < self.total_copies: self.available_copies += 1 return True return False def get_info(self): return (f"《{self.title}》 - {self.author} " f"(ISBN: {self.isbn}) " f"可用: {self.available_copies}/{self.total_copies}") @classmethod def get_total_books_count(cls): return cls.total_books class Member: """会员类""" def __init__(self, member_id, name): self.member_id = member_id self.name = name self.borrowed_books = [] # 借阅的图书列表 def borrow_book(self, book): """借书""" if len(self.borrowed_books) >= 5: print(f"{self.name} 已达到最大借书数量(5本)") return False if book.borrow(): self.borrowed_books.append(book) print(f"{self.name} 成功借阅 《{book.title}》") return True else: print(f"《{book.title}》 暂无可用副本") return False def return_book(self, book): """还书""" if book in self.borrowed_books: book.return_book() self.borrowed_books.remove(book) print(f"{self.name} 成功归还 《{book.title}》") return True else: print(f"{self.name} 没有借阅 《{book.title}》") return False def display_borrowed_books(self): """显示借阅的书籍""" if not self.borrowed_books: print(f"{self.name} 没有借阅任何书籍") else: print(f"{self.name} 借阅的书籍:") for book in self.borrowed_books: print(f" - 《{book.title}》") class Library: """图书馆类""" def __init__(self, name): self.name = name self.books = [] # 图书列表 self.members = [] # 会员列表 def add_book(self, book): """添加图书""" self.books.append(book) print(f"添加图书: 《{book.title}》") def register_member(self, member): """注册会员""" self.members.append(member) print(f"注册会员: {member.name}") def find_book(self, title): """查找图书""" for book in self.books: if book.title.lower() == title.lower(): return book return None def find_member(self, member_id): """查找会员""" for member in self.members: if member.member_id == member_id: return member return None def display_all_books(self): """显示所有图书""" print(f"\n=== {self.name} 图书列表 ===") if not self.books: print("暂无图书") else: for book in self.books: print(f" {book.get_info()}") def display_all_members(self): """显示所有会员""" print(f"\n=== {self.name} 会员列表 ===") if not self.members: print("暂无会员") else: for member in self.members: print(f" 会员ID: {member.member_id}, 姓名: {member.name}") # 测试图书馆系统 def main(): # 创建图书馆 library = Library("市立图书馆") # 添加图书 book1 = Book("Python编程入门", "张三", "978-1-123456-78-9", 3) book2 = Book("数据结构与算法", "李四", "978-1-987654-32-1", 2) book3 = Book("人工智能基础", "王五", "978-1-111111-11-1", 1) library.add_book(book1) library.add_book(book2) library.add_book(book3) # 注册会员 member1 = Member("M001", "小明") member2 = Member("M002", "小红") library.register_member(member1) library.register_member(member2) # 显示初始状态 library.display_all_books() library.display_all_members() print("\n=== 借书操作 ===") # 借书 member1.borrow_book(book1) member1.borrow_book(book2) member2.borrow_book(book1) member2.borrow_book(book3) print("\n=== 当前借阅情况 ===") member1.display_borrowed_books() member2.display_borrowed_books() library.display_all_books() print("\n=== 还书操作 ===") # 还书 member1.return_book(book1) member2.return_book(book3) print("\n=== 最终状态 ===") member1.display_borrowed_books() member2.display_borrowed_books() library.display_all_books() print(f"\n图书馆总图书数量: {Book.get_total_books_count()}") if __name__ == "__main__": main()完成以下测试：我能定义类和创建对象我理解构造函数 init 的作用我能使用封装来保护数据我理解继承的概念并能创建子类我知道如何重写父类方法我理解多态的概念我能区分实例方法、类方法和静态方法我成功运行了图书馆管理系统我能用面向对象思维解决实际问题模块化：import机制，编写自己的模块标准库探索：os, sys, datetime, random高级数据结构：collections模块函数进阶：lambda, map, filter, reduce列表推导式：高效处理数据虚拟环境：venv使用，依赖管理小Boss战：项目：图书馆管理系统图书类设计(书名、作者、状态)借书还书功能图书查询功能
Python 打怪升级之路：从新手到专家阶段一：新手村 (Level 1-10)目标：掌握基础语法，能写简单脚本任务清单：环境搭建：安装Python，配置开发环境(VSCode/PyCharm)基础语法：变量# 变量赋值 name = "小明" # 字符串 - 存储文本 age = 20 # 整数 - 存储整数 height = 1.75 # 浮点数 - 存储小数 is_student = True # 布尔值 - 存储True或False # 打印变量 print(name) # 输出: 小明 print(age) # 输出: 20 数据类型# 1. 字符串 (str) - 用引号包围 name = "Python" message = 'Hello World' # 2. 整数 (int) - 没有小数点的数字 age = 25 year = 2024 # 3. 浮点数 (float) - 有小数点的数字 price = 19.99 temperature = 36.5 # 4. 布尔值 (bool) - 只有两个值 is_raining = True is_sunny = False运算符#数学运算符 a = 10 b = 3 print(a + b) # 加法: 13 print(a - b) # 减法: 7 print(a * b) # 乘法: 30 print(a / b) # 除法: 3.333... print(a // b) # 整除: 3 print(a % b) # 取余: 1 print(a ** b) # 幂运算: 1000 #比较运算符 x = 5 y = 10 print(x == y) # 等于: False print(x != y) # 不等于: True print(x > y) # 大于: False print(x < y) # 小于: True print(x >= 5) # 大于等于: True我能创建变量并给它们赋值我能区分字符串、整数、浮点数、布尔值我能使用基本的数学运算符我能连接字符串我能使用input()获取用户输入我能使用print()输出结果我成功运行了简易计算器程序流程控制：if-else条件判断# 多条件判断 score = 85 if score >= 90: print("优秀！") elif score >= 80: print("良好！") elif score >= 60: print("及格！") else: print("不及格！")and，or，not# and: 两个条件都要满足 age = 20 has_license = True if age >= 18 and has_license: print("可以开车！") else: print("不能开车！") # or: 满足其中一个条件即可 is_weekend = True is_holiday = False if is_weekend or is_holiday: print("今天是休息日！") else: print("今天是工作日！") # not: 取反 is_raining = False if not is_raining: print("天气晴朗，可以出门！") else: print("下雨了，带伞！")for循环# 遍历水果列表 fruits = ["苹果", "香蕉", "橙子", "草莓"] for fruit in fruits: print(f"我喜欢吃{fruit}") # 输出： # 我喜欢吃苹果 # 我喜欢吃香蕉 # 我喜欢吃橙子 # 我喜欢吃草莓while循环# 计数器循环 count = 1 while count <= 5: print(f"这是第{count}次循环") count += 1 # 重要：不要忘记改变条件，否则会无限循环！ # 输出： # 这是第1次循环 # 这是第2次循环 # ...我能使用if-elif-else进行条件判断我理解and、or、not逻辑运算符我能使用for循环遍历列表和range我能使用while循环进行重复操作我知道break和continue的区别我成功运行了石头剪刀布游戏我能解释代码缩进的重要性数据结构：列表# 创建列表 fruits = ["苹果", "香蕉", "橙子", "草莓"] numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] print(fruits) # ['苹果', '香蕉', '橙子', '草莓'] print(numbers) # [1, 2, 3, 4, 5] # 索引访问（从0开始） fruits = ["苹果", "香蕉", "橙子", "草莓"] print(fruits[0]) # 苹果 (第一个) print(fruits[1]) # 香蕉 print(fruits[-1]) # 草莓 (最后一个) print(fruits[-2]) # 橙子 (倒数第二个) # 切片操作 [开始:结束:步长] numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(numbers[2:5]) # [2, 3, 4] (索引2到4) print(numbers[:3]) # [0, 1, 2] (从开始到索引2) print(numbers[5:]) # [5, 6, 7, 8, 9] (从索引5到最后) print(numbers[::2]) # [0, 2, 4, 6, 8] (每隔一个取一个) # 修改元素 fruits = ["苹果", "香蕉", "橙子"] fruits[1] = "葡萄" # 修改第二个元素 print(fruits) # ['苹果', '葡萄', '橙子'] # 添加元素 fruits.append("西瓜") # 在末尾添加 fruits.insert(1, "桃子") # 在指定位置插入 print(fruits) # ['苹果', '桃子', '葡萄', '橙子', '西瓜'] # 删除元素 removed_fruit = fruits.pop() # 删除最后一个元素 print(f"删除了: {removed_fruit}") # 删除了: 西瓜 print(fruits) # ['苹果', '桃子', '葡萄', '橙子'] fruits.remove("葡萄") # 删除指定元素 del fruits[0] # 删除指定位置元素 print(fruits) # ['桃子', '橙子'] # 创建一个学生成绩管理系统 students = ["小明", "小红", "小刚"] scores = [85, 92, 78] print("=== 学生成绩管理系统 ===") print(f"学生列表: {students}") print(f"成绩列表: {scores}") # 添加新学生 new_student = input("请输入新学生姓名: ") new_score = int(input("请输入该学生成绩: ")) students.append(new_student) scores.append(new_score) print(f"更新后的学生列表: {students}") print(f"更新后的成绩列表: {scores}") # 查询学生成绩 query_name = input("请输入要查询的学生姓名: ") if query_name in students: index = students.index(query_name) print(f"{query_name}的成绩是: {scores[index]}") else: print("找不到该学生！")字典# 创建字典 student = { "name": "小明", "age": 18, "grade": "高三", "subjects": ["数学", "物理", "英语"] } # 访问值 print(student["name"]) # 小明 print(student.get("age")) # 18 (推荐使用get，避免KeyError) # 如果键不存在，get返回None，而直接访问会报错 print(student.get("height")) # None # print(student["height"]) # 这会报错！ # 添加和修改 student = {"name": "小明", "age": 18} student["grade"] = "高三" # 添加新键值对 student["age"] = 19 # 修改已有键的值 print(student) # {'name': '小明', 'age': 19, 'grade': '高三'} # 删除 del student["grade"] # 删除键值对 age = student.pop("age") # 删除并返回值 print(f"删除的年龄: {age}") # 删除的年龄: 19 print(student) # {'name': '小明'} # 遍历字典 student = {"name": "小明", "age": 18, "grade": "高三"} for key in student: # 遍历键 print(f"{key}: {student[key]}") for key, value in student.items(): # 同时遍历键和值 print(f"{key}: {value}") # 创建一个简单的电话簿 phonebook = { "张三": "13800138000", "李四": "13900139000", "王五": "13700137000" } print("=== 简易电话簿 ===") while True: print("\n1. 查看所有联系人") print("2. 添加联系人") print("3. 查找联系人") print("4. 删除联系人") print("5. 退出") choice = input("请选择操作 (1-5): ") if choice == "1": print("\n所有联系人:") for name, phone in phonebook.items(): print(f"{name}: {phone}") elif choice == "2": name = input("请输入联系人姓名: ") phone = input("请输入电话号码: ") phonebook[name] = phone print(f"已添加 {name}") elif choice == "3": name = input("请输入要查找的姓名: ") if name in phonebook: print(f"{name}的电话是: {phonebook[name]}") else: print("联系人不存在！") elif choice == "4": name = input("请输入要删除的姓名: ") if name in phonebook: del phonebook[name] print(f"已删除 {name}") else: print("联系人不存在！") elif choice == "5": print("再见！") break else: print("无效选择！")元组# 创建元组 colors = ("红色", "绿色", "蓝色") coordinates = (10, 20) print(colors) # ('红色', '绿色', '蓝色') print(coordinates) # (10, 20) # 访问元素（和列表类似） print(colors[0]) # 红色 print(colors[-1]) # 蓝色 # 元组不可修改！ # colors[0] = "黄色" # 这行会报错！ # 元组解包 x, y = coordinates print(f"x: {x}, y: {y}") # x: 10, y: 20 # 单个元素的元组（注意逗号） single_tuple = (42,) # 有逗号是元组 not_tuple = (42) # 没有逗号就是普通数字 print(type(single_tuple)) # <class 'tuple'> print(type(not_tuple)) # <class 'int'> # 使用元组处理坐标 point1 = (3, 4) point2 = (6, 8) # 计算两点之间的距离 def calculate_distance(p1, p2): x1, y1 = p1 x2, y2 = p2 distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 return distance distance = calculate_distance(point1, point2) print(f"点{point1}和点{point2}之间的距离是: {distance:.2f}")集合# 创建集合 fruits = {"苹果", "香蕉", "橙子", "苹果"} # 重复的"苹果"会被自动去重 numbers = set([1, 2, 3, 2, 1]) # 从列表创建集合 print(fruits) # {'橙子', '香蕉', '苹果'} (顺序可能不同) print(numbers) # {1, 2, 3} # 集合操作 set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 | set2) # 并集: {1, 2, 3, 4, 5, 6, 7, 8} print(set1 & set2) # 交集: {4, 5} print(set1 - set2) # 差集: {1, 2, 3} print(set1 ^ set2) # 对称差集: {1, 2, 3, 6, 7, 8} # 集合方法 fruits.add("西瓜") # 添加元素 fruits.remove("香蕉") # 删除元素（如果不存在会报错） fruits.discard("芒果") # 删除元素（如果不存在不会报错） # 使用集合分析数据 # 两个班级的学生名单 class_a = {"小明", "小红", "小刚", "小丽", "小王"} class_b = {"小张", "小红", "小刚", "小赵", "小钱"} print("A班学生:", class_a) print("B班学生:", class_b) print("两班共有学生:", class_a | class_b) print("两班都有的学生:", class_a & class_b) print("只在A班的学生:", class_a - class_b) print("只在B班的学生:", class_b - class_a) print("不同时在兩班的学生:", class_a ^ class_b)我能创建和操作列表（添加、删除、访问元素）我理解列表切片操作我能使用字典存储和访问键值对我能遍历字典的键和值我理解元组的特点（不可变）我能使用元组解包我理解集合的特点（无序、不重复）我能进行集合运算（并集、交集等）我成功运行了学生管理系统函数编写：定义函数# 定义函数 def say_hello(): print("你好！") print("欢迎学习Python函数！") # 调用函数 say_hello() # 输出两行问候语 # 带一个参数 def greet(name): print(f"你好，{name}！") greet("小明") # 你好，小明！ greet("小红") # 你好，小红！ # 带多个参数 def introduce(name, age, city): print(f"我叫{name}，今年{age}岁，来自{city}。") introduce("张三", 20, "北京") # 我叫张三，今年20岁，来自北京。 # 1. 编写一个打印三角形的函数 def print_triangle(size): for i in range(1, size + 1): print("*" * i) # 测试 print_triangle(5) # 2. 编写个人信息函数 def print_person_info(name, age, hobby): print(f"姓名: {name}") print(f"年龄: {age}") print(f"爱好: {hobby}") print("-" * 20) # 测试 print_person_info("小明", 18, "篮球") print_person_info("小红", 19, "阅读")参数传递# 有默认值的参数 def greet(name, message="你好"): print(f"{message}，{name}！") greet("小明") # 你好，小明！ greet("小红", "欢迎") # 欢迎，小红！ greet("小刚", message="再见") # 再见，小刚！ # 默认参数必须在非默认参数后面 def create_student(name, age, grade="一年级"): return f"学生: {name}, 年龄: {age}, 年级: {grade}" print(create_student("张三", 18)) # 使用默认年级 print(create_student("李四", 19, "二年级")) # 指定年级 # 使用参数名调用，顺序不重要 def describe_pet(pet_name, animal_type="狗"): print(f"我有一只{animal_type}，它叫{pet_name}。") # 不同的调用方式 describe_pet("旺财") # 我有一只狗，它叫旺财。 describe_pet("咪咪", "猫") # 我有一只猫，它叫咪咪。 describe_pet(animal_type="仓鼠", pet_name="小灰") # 我有一只仓鼠，它叫小灰。 ########### def create_greeting(name, time_of_day="", formal=False, emoji=""): greeting = "" if formal: greeting += "尊敬的" else: greeting += "嗨，" greeting += name if time_of_day: greeting += f"，{time_of_day}好" greeting += "！" if emoji: greeting += f" {emoji}" return greeting # 测试各种问候方式 print(create_greeting("小明")) print(create_greeting("张经理", formal=True)) print(create_greeting("小红", "早上", emoji="6")) print(create_greeting("小王", "晚上", True, "6"))返回值# 计算面积的函数 def calculate_area(length, width): area = length * width return area # 返回计算结果 # 使用返回值 room_area = calculate_area(5, 4) print(f"房间面积: {room_area}平方米") # 房间面积: 20平方米 # 直接在表达式中使用 total_area = calculate_area(3, 3) + calculate_area(4, 4) print(f"总面积: {total_area}平方米") # 总面积: 25平方米 # 返回多个值（实际上返回的是元组） def calculate_circle(radius): circumference = 2 * 3.14159 * radius # 周长 area = 3.14159 * radius ** 2 # 面积 return circumference, area # 接收多个返回值 circ, area = calculate_circle(5) print(f"周长: {circ:.2f}") # 周长: 31.42 print(f"面积: {area:.2f}") # 面积: 78.54 # 编写一个四则运算计算器 def calculator(num1, num2, operation): if operation == "+": return num1 + num2 elif operation == "-": return num1 - num2 elif operation == "*": return num1 * num2 elif operation == "/": if num2 != 0: return num1 / num2 else: return "错误：除数不能为0" else: return "错误：不支持的操作" # 测试 print(calculator(10, 5, "+")) # 15 print(calculator(10, 5, "-")) # 5 print(calculator(10, 5, "*")) # 50 print(calculator(10, 5, "/")) # 2.0 print(calculator(10, 0, "/")) # 错误：除数不能为0变量的作用域# 全局变量 global_score = 100 def test_scope(): # 局部变量 local_score = 50 print(f"函数内局部变量: {local_score}") # 50 print(f"函数内访问全局变量: {global_score}") # 100 # 修改全局变量需要使用 global 关键字 global global_score global_score = 200 test_scope() print(f"函数外全局变量: {global_score}") # 200 # print(local_score) # 这行会报错，因为local_score是局部变量 def create_counter(): count = 0 # 闭包中的变量 def counter(): nonlocal count # 声明使用外部函数的变量 count += 1 return count return counter # 创建两个独立的计数器 counter1 = create_counter() counter2 = create_counter() print(counter1()) # 1 print(counter1()) # 2 print(counter2()) # 1 (独立的计数器) print(counter1()) # 3递归函数# 计算阶乘 n! = n * (n-1) * ... * 1 def factorial(n): if n == 1: # 基线条件 return 1 else: # 递归条件 return n * factorial(n - 1) print(factorial(5)) # 120 (5*4*3*2*1) # 斐波那契数列 def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) # 打印前10个斐波那契数 for i in range(10): print(fibonacci(i), end=" ") # 0 1 1 2 3 5 8 13 21 34def sum_digits(n): """ 递归计算数字各位之和 例如：sum_digits(123) = 1 + 2 + 3 = 6 """ if n < 10: return n else: return n % 10 + sum_digits(n // 10) # 测试 print(sum_digits(123)) # 6 print(sum_digits(9876)) # 30 (9+8+7+6)小结# 用函数重构学生成绩管理系统 students = [] def show_menu(): """显示菜单""" print("\n=== 学生成绩管理系统 ===") print("1. 添加学生") print("2. 显示所有学生") print("3. 查询学生") print("4. 添加成绩") print("5. 成绩分析") print("6. 退出") def add_student(): """添加学生""" name = input("请输入学生姓名: ") age = int(input("请输入学生年龄: ")) # 检查学生是否已存在 if find_student(name) is not None: print("该学生已存在！") return student = { "name": name, "age": age, "scores": {} } students.append(student) print(f"成功添加学生: {name}") def find_student(name): """查找学生，返回学生对象或None""" for student in students: if student["name"] == name: return student return None def show_all_students(): """显示所有学生""" if not students: print("暂无学生信息！") return print("\n=== 所有学生信息 ===") for student in students: print(f"姓名: {student['name']}, 年龄: {student['age']}") if student['scores']: print(" 成绩:", student['scores']) print("-" * 30) def query_student(): """查询学生信息""" name = input("请输入要查询的学生姓名: ") student = find_student(name) if student: print(f"\n找到学生: {student['name']}") print(f"年龄: {student['age']}") if student['scores']: print("成绩详情:") for subject, score in student['scores'].items(): print(f" {subject}: {score}") else: print("暂无成绩信息") else: print("找不到该学生！") def add_score(): """添加学生成绩""" name = input("请输入学生姓名: ") student = find_student(name) if student: subject = input("请输入科目: ") score = float(input("请输入成绩: ")) student["scores"][subject] = score print(f"已为{name}添加{subject}成绩: {score}") else: print("找不到该学生！") def analyze_scores(): """成绩分析""" if not students: print("没有学生数据！") return all_scores = [] for student in students: all_scores.extend(student['scores'].values()) if all_scores: avg_score = sum(all_scores) / len(all_scores) max_score = max(all_scores) min_score = min(all_scores) print(f"\n=== 成绩分析 ===") print(f"学生总数: {len(students)}") print(f"成绩记录数: {len(all_scores)}") print(f"平均分: {avg_score:.2f}") print(f"最高分: {max_score}") print(f"最低分: {min_score}") else: print("暂无成绩数据！") # 主程序 def main(): while True: show_menu() choice = input("请选择操作 (1-6): ") if choice == "1": add_student() elif choice == "2": show_all_students() elif choice == "3": query_student() elif choice == "4": add_score() elif choice == "5": analyze_scores() elif choice == "6": print("再见！") break else: print("无效选择，请重新输入！") # 启动程序 if __name__ == "__main__": main()我能定义和调用简单的函数我能编写带参数的函数我理解返回值的作用，并能使用return语句我知道默认参数和关键字参数的用法我理解局部变量和全局变量的区别我能编写简单的递归函数我成功运行了函数版的学生管理系统我能将复杂任务分解成多个函数文件操作：读写txt# 最基础的读取方式 file = open('example.txt', 'r', encoding='utf-8') content = file.read() print(content) file.close() # 使用 with 语句（推荐！自动关闭文件） with open('example.txt', 'r', encoding='utf-8') as file: content = file.read() print(content) # 文件会自动关闭，不需要手动调用 file.close()# 读取所有行到列表 with open('example.txt', 'r', encoding='utf-8') as file: lines = file.readlines() for line in lines: print(line.strip()) # strip() 去除换行符和空格 # 直接遍历文件对象（内存更友好） with open('example.txt', 'r', encoding='utf-8') as file: for line in file: print(f"行内容: {line.strip()}")# 首先创建一个测试文件 with open('test.txt', 'w', encoding='utf-8') as file: file.write("这是第一行\n") file.write("这是第二行\n") file.write("这是第三行\n") print("文件写入完成！") # 然后读取它 with open('test.txt', 'r', encoding='utf-8') as file: content = file.read() print("文件内容：") print(content)# 'w' 模式会覆盖原有内容 with open('diary.txt', 'w', encoding='utf-8') as file: file.write("2024年学习日记\n") file.write("今天学习了Python文件操作\n") file.write("感觉很有趣！\n") print("日记写入完成！")# 'a' 模式会在文件末尾追加内容 with open('diary.txt', 'a', encoding='utf-8') as file: file.write("\n第二天：\n") file.write("继续学习Python\n") file.write("掌握了文件读写操作\n") print("日记追加完成！")def write_diary(): """写日记功能""" date = input("请输入日期（如：2024-01-01）: ") content = input("请输入日记内容: ") weather = input("请输入天气: ") with open('my_diary.txt', 'a', encoding='utf-8') as file: file.write(f"\n=== {date} ===\n") file.write(f"天气: {weather}\n") file.write(f"内容: {content}\n") file.write("-" * 30 + "\n") print("日记保存成功！") def read_diary(): """读日记功能""" try: with open('my_diary.txt', 'r', encoding='utf-8') as file: content = file.read() if content: print("\n=== 我的日记 ===") print(content) else: print("还没有日记呢！") except FileNotFoundError: print("还没有日记呢，快去写一篇吧！") # 主程序 while True: print("\n=== 简易日记本 ===") print("1. 写日记") print("2. 读日记") print("3. 退出") choice = input("请选择 (1-3): ") if choice == '1': write_diary() elif choice == '2': read_diary() elif choice == '3': print("再见！") break else: print("无效选择！")读写csvimport csv # 写入CSV文件 students = [ ['姓名', '年龄', '成绩'], ['小明', '18', '95'], ['小红', '17', '88'], ['小刚', '19', '92'] ] with open('students.csv', 'w', encoding='utf-8', newline='') as file: writer = csv.writer(file) writer.writerows(students) print("CSV文件写入完成！")import csv # 读取CSV文件 with open('students.csv', 'r', encoding='utf-8') as file: reader = csv.reader(file) for row in reader: print(f"行: {row}") # 使用DictReader（更推荐） print("\n使用DictReader读取：") with open('students.csv', 'r', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: print(f"学生: {row['姓名']}, 年龄: {row['年龄']}, 成绩: {row['成绩']}")读写JSONimport json # Python数据结构 student_data = { "students": [ {"name": "小明", "age": 18, "subjects": ["数学", "物理"]}, {"name": "小红", "age": 17, "subjects": ["语文", "英语"]}, {"name": "小刚", "age": 19, "subjects": ["化学", "生物"]} ], "class_name": "高三一班" } # 写入JSON文件 with open('class_data.json', 'w', encoding='utf-8') as file: json.dump(student_data, file, ensure_ascii=False, indent=2) print("JSON文件写入完成！")import json # 读取JSON文件 with open('class_data.json', 'r', encoding='utf-8') as file: data = json.load(file) print(f"班级: {data['class_name']}") print("学生列表:") for student in data['students']: print(f"- {student['name']}, {student['age']}岁, 科目: {', '.join(student['subjects'])}")#配置管理器 import json import os def load_config(): """加载配置文件""" if os.path.exists('config.json'): with open('config.json', 'r', encoding='utf-8') as file: return json.load(file) else: # 默认配置 return { "language": "zh-CN", "theme": "light", "font_size": 14, "auto_save": True } def save_config(config): """保存配置文件""" with open('config.json', 'w', encoding='utf-8') as file: json.dump(config, file, ensure_ascii=False, indent=2) print("配置已保存！") def show_config(config): """显示当前配置""" print("\n=== 当前配置 ===") for key, value in config.items(): print(f"{key}: {value}") def change_config(config): """修改配置""" print("\n可修改的配置项:") keys = list(config.keys()) for i, key in enumerate(keys, 1): print(f"{i}. {key}: {config[key]}") try: choice = int(input("请选择要修改的配置项编号: ")) - 1 if 0 <= choice < len(keys): key = keys[choice] new_value = input(f"请输入新的 {key} 值: ") # 类型转换 if isinstance(config[key], bool): config[key] = new_value.lower() in ['true', '1', 'yes', '是'] elif isinstance(config[key], int): config[key] = int(new_value) else: config[key] = new_value print("修改成功！") else: print("无效选择！") except ValueError: print("请输入有效数字！") # 主程序 config = load_config() while True: print("\n=== 配置管理器 ===") print("1. 查看配置") print("2. 修改配置") print("3. 保存配置") print("4. 退出") choice = input("请选择 (1-4): ") if choice == '1': show_config(config) elif choice == '2': change_config(config) elif choice == '3': save_config(config) elif choice == '4': print("再见！") break else: print("无效选择！")异常处理与文件操作def safe_file_operations(): """安全的文件操作""" filename = input("请输入文件名: ") try: with open(filename, 'r', encoding='utf-8') as file: content = file.read() print("文件内容:") print(content) except FileNotFoundError: print(f"错误：找不到文件 {filename}") except PermissionError: print(f"错误：没有权限读取文件 {filename}") except UnicodeDecodeError: print("错误：文件编码问题，请尝试其他编码") except Exception as e: print(f"发生未知错误: {e}") else: print("文件读取成功！") finally: print("文件操作完成") # 测试 safe_file_operations()#文件备份工具 import os import shutil from datetime import datetime def backup_file(): """备份文件""" source_file = input("请输入要备份的文件路径: ") if not os.path.exists(source_file): print("文件不存在！") return # 生成备份文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") base_name = os.path.basename(source_file) backup_name = f"backup_{timestamp}_{base_name}" try: shutil.copy2(source_file, backup_name) print(f"文件备份成功: {backup_name}") except Exception as e: print(f"备份失败: {e}") def list_backups(): """列出备份文件""" backup_files = [f for f in os.listdir() if f.startswith('backup_')] if not backup_files: print("没有找到备份文件") return print("\n=== 备份文件列表 ===") for i, file in enumerate(sorted(backup_files), 1): size = os.path.getsize(file) print(f"{i}. {file} ({size} 字节)") def restore_backup(): """恢复备份""" list_backups() backup_files = [f for f in os.listdir() if f.startswith('backup_')] if not backup_files: return try: choice = int(input("请选择要恢复的备份编号: ")) - 1 if 0 <= choice < len(backup_files): backup_file = backup_files[choice] original_name = backup_file.split('_', 2)[2] # 提取原始文件名 confirm = input(f"确定要恢复为 {original_name} 吗？(y/n): ") if confirm.lower() == 'y': shutil.copy2(backup_file, original_name) print("恢复成功！") else: print("无效选择！") except ValueError: print("请输入有效数字！") # 主程序 while True: print("\n=== 文件备份工具 ===") print("1. 备份文件") print("2. 查看备份") print("3. 恢复备份") print("4. 退出") choice = input("请选择 (1-4): ") if choice == '1': backup_file() elif choice == '2': list_backups() elif choice == '3': restore_backup() elif choice == '4': print("再见！") break else: print("无效选择！")#个人知识管理系统 import json import os from datetime import datetime KNOWLEDGE_FILE = 'knowledge_base.json' def load_knowledge_base(): """加载知识库""" if os.path.exists(KNOWLEDGE_FILE): with open(KNOWLEDGE_FILE, 'r', encoding='utf-8') as file: return json.load(file) else: return {"categories": {}} def save_knowledge_base(kb): """保存知识库""" with open(KNOWLEDGE_FILE, 'w', encoding='utf-8') as file: json.dump(kb, file, ensure_ascii=False, indent=2) def add_category(kb): """添加分类""" category = input("请输入分类名称: ") if category not in kb['categories']: kb['categories'][category] = [] print(f"分类 '{category}' 添加成功！") else: print("分类已存在！") def add_knowledge(kb): """添加知识点""" if not kb['categories']: print("请先创建分类！") return print("可用分类:") categories = list(kb['categories'].keys()) for i, cat in enumerate(categories, 1): print(f"{i}. {cat}") try: choice = int(input("请选择分类编号: ")) - 1 if 0 <= choice < len(categories): category = categories[choice] title = input("请输入知识点标题: ") content = input("请输入知识点内容: ") knowledge = { "title": title, "content": content, "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S") } kb['categories'][category].append(knowledge) print("知识点添加成功！") else: print("无效选择！") except ValueError: print("请输入有效数字！") def search_knowledge(kb): """搜索知识点""" keyword = input("请输入搜索关键词: ").lower() found = False for category, knowledge_list in kb['categories'].items(): for knowledge in knowledge_list: if (keyword in knowledge['title'].lower() or keyword in knowledge['content'].lower()): print(f"\n分类: {category}") print(f"标题: {knowledge['title']}") print(f"内容: {knowledge['content']}") print(f"创建时间: {knowledge['created_at']}") print("-" * 40) found = True if not found: print("没有找到相关知识点！") def export_to_text(kb): """导出为文本文件""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"knowledge_export_{timestamp}.txt" with open(filename, 'w', encoding='utf-8') as file: file.write("=== 个人知识库 ===\n\n") for category, knowledge_list in kb['categories'].items(): file.write(f"## {category}\n") for knowledge in knowledge_list: file.write(f"标题: {knowledge['title']}\n") file.write(f"内容: {knowledge['content']}\n") file.write(f"时间: {knowledge['created_at']}\n") file.write("-" * 30 + "\n") file.write("\n") print(f"知识库已导出到: {filename}") # 主程序 knowledge_base = load_knowledge_base() while True: print("\n=== 个人知识管理系统 ===") print("1. 添加分类") print("2. 添加知识点") print("3. 搜索知识点") print("4. 导出知识库") print("5. 退出") choice = input("请选择 (1-5): ") if choice == '1': add_category(knowledge_base) elif choice == '2': add_knowledge(knowledge_base) elif choice == '3': search_knowledge(knowledge_base) elif choice == '4': export_to_text(knowledge_base) elif choice == '5': save_knowledge_base(knowledge_base) print("知识库已保存，再见！") break else: print("无效选择！")我能用 with 语句安全地读写文件我知道 'r', 'w', 'a' 模式的区别我能读取和写入CSV文件我能使用json模块处理JSON数据我能处理文件操作中的异常我理解文件编码的重要性我成功运行了个人知识管理系统我能将数据持久化保存到文件中异常处理：try-except基本用法# 处理除零错误 try: num1 = int(input("请输入被除数: ")) num2 = int(input("请输入除数: ")) result = num1 / num2 print(f"结果是: {result}") except ZeroDivisionError: print("错误：除数不能为零！") print("程序继续运行...")多个异常try: num = int(input("请输入一个数字: ")) result = 10 / num print(f"10 / {num} = {result}") except ValueError: print("错误：请输入有效的数字！") except ZeroDivisionError: print("错误：不能除以零！") except Exception as e: print(f"发生了未知错误: {e}")try-except-else-finallydef read_file_safely(filename): """安全地读取文件""" try: file = open(filename, 'r', encoding='utf-8') content = file.read() except FileNotFoundError: print(f"错误：找不到文件 {filename}") except PermissionError: print(f"错误：没有权限读取文件 {filename}") except UnicodeDecodeError: print("错误：文件编码问题") else: print("文件读取成功！") print(f"文件内容:\n{content}") return content finally: # 无论是否发生异常都会执行 try: file.close() print("文件已关闭") except: pass # 如果file没有定义，忽略错误 # 测试 read_file_safely('test.txt')def validate_user_registration(): """用户注册验证""" try: username = input("请输入用户名: ") password = input("请输入密码: ") age = int(input("请输入年龄: ")) # 验证规则 if len(username) < 3: raise ValueError("用户名至少3个字符") if len(password) < 6: raise ValueError("密码至少6个字符") if age < 0 or age > 150: raise ValueError("年龄必须在0-150之间") except ValueError as e: print(f"输入验证失败: {e}") return False except Exception as e: print(f"注册过程中发生错误: {e}") return False else: print("用户注册成功！") print(f"用户名: {username}") print(f"年龄: {age}") return True finally: print("注册流程结束") # 测试 if validate_user_registration(): print("可以继续下一步操作") else: print("请重新填写注册信息")自定义异常# 自定义异常类 class InsufficientFundsError(Exception): """余额不足异常""" def __init__(self, balance, amount): self.balance = balance self.amount = amount self.message = f"余额不足！当前余额: {balance}，尝试取款: {amount}" super().__init__(self.message) class InvalidAmountError(Exception): """无效金额异常""" pass class BankAccount: """银行账户类""" def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): """存款""" if amount <= 0: raise InvalidAmountError("存款金额必须大于0") self.balance += amount print(f"存款成功！当前余额: {self.balance}") def withdraw(self, amount): """取款""" if amount <= 0: raise InvalidAmountError("取款金额必须大于0") if amount > self.balance: raise InsufficientFundsError(self.balance, amount) self.balance -= amount print(f"取款成功！当前余额: {self.balance}") return amount # 测试银行账户 def test_bank_account(): account = BankAccount(1000) try: account.deposit(500) account.withdraw(200) account.withdraw(2000) # 这会引发异常 except InsufficientFundsError as e: print(f"取款失败: {e}") except InvalidAmountError as e: print(f"金额错误: {e}") except Exception as e: print(f"未知错误: {e}") test_bank_account()断言 (Assert)def calculate_bmi(weight, height): """ 计算BMI指数 weight: 体重(kg) height: 身高(m) """ # 使用断言验证输入 assert weight > 0, "体重必须大于0" assert height > 0, "身高必须大于0" assert height < 3, "身高应该以米为单位" bmi = weight / (height ** 2) # 验证计算结果 assert 10 <= bmi <= 60, f"BMI值异常: {bmi}" return bmi def bmi_category(bmi): """BMI分类""" assert bmi > 0, "BMI必须大于0" if bmi < 18.5: return "偏瘦" elif bmi < 24: return "正常" elif bmi < 28: return "超重" else: return "肥胖" # 测试BMI计算 try: weight = float(input("请输入体重(kg): ")) height = float(input("请输入身高(m): ")) bmi = calculate_bmi(weight, height) category = bmi_category(bmi) print(f"你的BMI是: {bmi:.2f}") print(f"体重状况: {category}") except AssertionError as e: print(f"输入数据错误: {e}") except ValueError: print("请输入有效的数字！") except Exception as e: print(f"计算错误: {e}")小Boss战：项目：个人记账系统记录收入支出统计每日总额数据保存到文件# personal_finance_system.py import json import os from datetime import datetime, date from typing import Dict, List, Optional class FinanceSystem: def __init__(self, data_file: str = "finance_data.json"): self.data_file = data_file self.data = self._load_data() def _load_data(self) -> Dict: """加载数据文件""" try: if os.path.exists(self.data_file): with open(self.data_file, 'r', encoding='utf-8') as f: return json.load(f) else: return self._create_default_data() except Exception as e: print(f" 加载数据失败: {e}") return self._create_default_data() def _create_default_data(self) -> Dict: """创建默认数据结构""" return { "version": "1.0", "created_at": datetime.now().isoformat(), "transactions": [], "categories": { "收入": ["工资", "奖金", "投资", "兼职", "其他"], "支出": ["餐饮", "交通", "购物", "娱乐", "医疗", "住房", "其他"] } } def _save_data(self) -> bool: """保存数据到文件""" try: with open(self.data_file, 'w', encoding='utf-8') as f: json.dump(self.data, f, ensure_ascii=False, indent=2) return True except Exception as e: print(f" 保存数据失败: {e}") return False def add_transaction(self, amount: float, trans_type: str, category: str, description: str = "") -> bool: """添加交易记录""" try: # 输入验证 if amount <= 0: print(" 金额必须大于0") return False if trans_type not in ["收入", "支出"]: print(" 类型必须是'收入'或'支出'") return False # 生成交易记录 transaction = { "id": datetime.now().strftime("%Y%m%d%H%M%S"), "type": trans_type, "category": category, "amount": round(amount, 2), "date": date.today().isoformat(), "time": datetime.now().strftime("%H:%M:%S"), "description": description, "created_at": datetime.now().isoformat() } # 添加到数据中 self.data["transactions"].append(transaction) # 保存数据 if self._save_data(): print(f" 交易记录添加成功！") return True else: # 回滚 self.data["transactions"].pop() print(" 保存失败，已回滚") return False except Exception as e: print(f" 添加交易失败: {e}") return False def get_daily_summary(self, target_date: str = None) -> Dict: """获取每日统计""" if target_date is None: target_date = date.today().isoformat() daily_transactions = [ t for t in self.data["transactions"] if t["date"] == target_date ] income = sum(t["amount"] for t in daily_transactions if t["type"] == "收入") expense = sum(t["amount"] for t in daily_transactions if t["type"] == "支出") balance = income - expense return { "date": target_date, "income": income, "expense": expense, "balance": balance, "transaction_count": len(daily_transactions), "transactions": daily_transactions } def get_category_summary(self, start_date: str, end_date: str) -> Dict: """获取分类统计""" transactions_in_range = [ t for t in self.data["transactions"] if start_date <= t["date"] <= end_date ] category_summary = {} for transaction in transactions_in_range: category = transaction["category"] amount = transaction["amount"] trans_type = transaction["type"] if category not in category_summary: category_summary[category] = { "income": 0, "expense": 0, "count": 0 } if trans_type == "收入": category_summary[category]["income"] += amount else: category_summary[category]["expense"] += amount category_summary[category]["count"] += 1 return category_summary def show_recent_transactions(self, limit: int = 10): """显示最近交易记录""" transactions = self.data["transactions"][-limit:] transactions.reverse() # 最新的在前面 if not transactions: print(" 暂无交易记录") return print(f"\n 最近{len(transactions)}笔交易:") print("=" * 80) print(f"{'日期':<12} {'时间':<8} {'类型':<4} {'金额':<10} {'分类':<8} {'备注'}") print("-" * 80) for transaction in transactions: amount_display = f"+{transaction['amount']:.2f}" if transaction['type'] == '收入' else f"-{transaction['amount']:.2f}" print(f"{transaction['date']:<12} {transaction['time']:<8} " f"{transaction['type']:<4} {amount_display:<10} " f"{transaction['category']:<8} {transaction['description']}") def show_detailed_summary(self, days: int = 7): """显示详细统计""" end_date = date.today() start_date = end_date - timedelta(days=days-1) print(f"\n {days}天统计汇总 ({start_date} 到 {end_date})") print("=" * 60) total_income = 0 total_expense = 0 total_transactions = 0 for single_date in (start_date + timedelta(n) for n in range(days)): date_str = single_date.isoformat() summary = self.get_daily_summary(date_str) if summary["transaction_count"] > 0: print(f"{date_str}: " f"收入{summary['income']:>8.2f} | " f"支出{summary['expense']:>8.2f} | " f"结余{summary['balance']:>8.2f} | " f"{summary['transaction_count']:>2}笔交易") total_income += summary['income'] total_expense += summary['expense'] total_transactions += summary['transaction_count'] print("-" * 60) print(f"总计: " f"收入{total_income:>8.2f} | " f"支出{total_expense:>8.2f} | " f"结余{total_income - total_expense:>8.2f} | " f"{total_transactions:>2}笔交易") def main(): """主程序""" system = FinanceSystem() while True: print("\n" + "="*50) print(" 个人记账系统") print("="*50) print("1. 记录收入") print("2. 记录支出") print("3. 查看今日统计") print("4. 查看最近交易") print("5. 查看周度报告") print("6. 分类统计") print("7. 退出") print("-"*50) choice = input("请选择操作 (1-7): ").strip() try: if choice == '1': # 记录收入 print("\n 记录收入") print("可用分类:", ", ".join(system.data["categories"]["收入"])) amount = float(input("收入金额: ")) category = input("收入分类: ") description = input("备注: ") system.add_transaction(amount, "收入", category, description) elif choice == '2': # 记录支出 print("\n 记录支出") print("可用分类:", ", ".join(system.data["categories"]["支出"])) amount = float(input("支出金额: ")) category = input("支出分类: ") description = input("备注: ") system.add_transaction(amount, "支出", category, description) elif choice == '3': # 今日统计 summary = system.get_daily_summary() print(f"\n 今日统计 ({summary['date']})") print(f" 收入: {summary['income']:.2f}") print(f" 支出: {summary['expense']:.2f}") print(f" 结余: {summary['balance']:.2f}") print(f" 交易笔数: {summary['transaction_count']}") elif choice == '4': # 最近交易 system.show_recent_transactions(10) elif choice == '5': # 周度报告 system.show_detailed_summary(7) elif choice == '6': # 分类统计 print("\n 分类统计") start_date = input("开始日期 (YYYY-MM-DD): ") or "2024-01-01" end_date = input("结束日期 (YYYY-MM-DD): ") or date.today().isoformat() category_summary = system.get_category_summary(start_date, end_date) print(f"\n分类统计 ({start_date} 到 {end_date})") print("-" * 50) for category, data in category_summary.items(): print(f"{category:<8}: 收入{data['income']:>8.2f} | " f"支出{data['expense']:>8.2f} | {data['count']:>2}笔") elif choice == '7': print(" 再见！") break else: print(" 无效选择，请重新输入！") except ValueError: print(" 输入格式错误，请检查金额格式") except KeyboardInterrupt: print("\n\n 程序被用户中断") break except Exception as e: print(f" 系统错误: {e}") # 确保timedelta被导入 from datetime import timedelta if __name__ == "__main__": main()我能使用 try-except 处理常见异常我理解 else 和 finally 的作用我能创建和使用自定义异常我知道如何使用断言进行调试我能结合日志记录进行异常处理我能编写健壮的程序处理各种错误情况我成功运行了健壮的学生管理系统我能预测并处理可能的运行时错误