Python 打怪升级之路:从新手到专家
阶段一:新手村 (Level 1-10)
目标:掌握基础语法,能写简单脚本
任务清单:

  1. 环境搭建:
    安装Python,配置开发环境(VSCode/PyCharm)
  2. 基础语法:
    变量

    # 变量赋值
    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()输出结果

我成功运行了简易计算器程序

  1. 流程控制:
    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的区别

我成功运行了石头剪刀布游戏

我能解释代码缩进的重要性

  1. 数据结构:
    列表

    # 创建列表
    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)

    我能创建和操作列表(添加、删除、访问元素)

我理解列表切片操作

我能使用字典存储和访问键值对

我能遍历字典的键和值

我理解元组的特点(不可变)

我能使用元组解包

我理解集合的特点(无序、不重复)

我能进行集合运算(并集、交集等)

我成功运行了学生管理系统

  1. 函数编写:
    定义函数

    # 定义函数
    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 34
def 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语句

我知道默认参数和关键字参数的用法

我理解局部变量和全局变量的区别

我能编写简单的递归函数

我成功运行了函数版的学生管理系统

我能将复杂任务分解成多个函数

  1. 文件操作:
    读写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("无效选择!")

读写csv

import 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['成绩']}")

读写JSON

import 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数据

我能处理文件操作中的异常

我理解文件编码的重要性

我成功运行了个人知识管理系统

我能将数据持久化保存到文件中

  1. 异常处理: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-finally

def 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 的作用

我能创建和使用自定义异常

我知道如何使用断言进行调试

我能结合日志记录进行异常处理

我能编写健壮的程序处理各种错误情况

我成功运行了健壮的学生管理系统

我能预测并处理可能的运行时错误