小朋友的Python冒险之旅

《小码农的Python冒险之旅》

前言:开启你的编程魔法世界

亲爱的小朋友们,欢迎来到Python编程的魔法世界!在这里,你将学会用代码创造奇迹,让计算机听从你的指令,创作出属于自己的游戏和程序。就像哈利·波特学习魔法咒语一样,我们将一起学习Python这门神奇的"编程语言"。

Python是一种非常友好的编程语言,它的名字来源于创造者喜欢的一个喜剧团体。Python就像是一位和蔼可亲的老师,用最简单的方式教会我们编程的奥秘。准备好了吗?让我们一起开始这段奇妙的冒险之旅!

第一章:认识你的新朋友Python

1.1 Python是什么?

想象一下,如果你想和来自不同国家的朋友交流,你需要学习他们的语言,对吗?同样的道理,如果我们想让计算机帮我们做事情,就需要学习计算机能够理解的语言——这就是编程语言。

Python就是众多编程语言中的一种,它特别适合初学者,因为:

  • 它的语法简单,就像在写英语句子

  • 它功能强大,可以做游戏、画图、计算数学题

  • 全世界有很多人都在使用它,包括谷歌、YouTube等大公司

1.2 安装Python魔法工具箱

在开始编程之前,我们需要在电脑上安装Python。这就像画画之前要准备好画笔和颜料一样。

安装步骤:

  1. 请爸爸妈妈帮你打开Python官方网站(python.org)

  2. 下载适合你电脑系统的Python版本

  3. 运行安装程序,记得勾选"Add Python to PATH"选项

  4. 安装完成后,我们还需要一个写代码的"魔法本"——推荐使用Thonny,这是专门为初学者设计的Python编辑器

1.3 第一个魔法咒语:Hello World!

现在让我们施展第一个Python魔法!打开Thonny,输入下面这行代码:

  
print("Hello, World!")
  

点击运行按钮,你会看到屏幕上出现了"Hello, World!"。恭喜你!你刚刚让计算机说出了它的第一句话!

让我们再试试其他的:

  
print("我叫小明")
  
print("我今年10岁")
  
print("我喜欢编程!")
  

看,计算机会按照你写的顺序,一句一句地显示出来。print()就像是一个魔法咒语,它能让计算机在屏幕上显示文字。括号里的内容要用引号包起来,这样Python才知道这是要显示的文字。

1.4 Python可以做数学题

Python不仅会说话,还是个数学小天才呢!试试看:

  
print(5 + 3)
  
print(10 - 4)
  
print(6 * 7)
  
print(20 / 4)
  

运行这段代码,你会发现Python帮你算出了所有答案。在Python中:

  • + 表示加法

  • - 表示减法

  • * 表示乘法

  • / 表示除法

你甚至可以让Python帮你算更复杂的题目:

  
print("小明有5个苹果,小红给了他3个,他现在有几个?")
  
print(5 + 3)
  

  
print("妈妈买了24个糖果,平均分给6个小朋友,每人能得到几个?")
  
print(24 / 6)
  

第二章:变量——神奇的储物盒

2.1 什么是变量?

在生活中,我们会用盒子来装东西,比如用铅笔盒装铅笔,用书包装书本。在Python中,变量就像是一个个神奇的盒子,可以用来存放各种信息。

  
my_name = "小明"
  
my_age = 10
  
my_height = 140.5
  

  
print(my_name)
  
print(my_age)
  
print(my_height)
  

在这个例子中:

  • my_name 是一个盒子,里面装着文字"小明"

  • my_age 是另一个盒子,里面装着数字10

  • my_height 也是一个盒子,装着小数140.5

2.2 给变量起名字的规则

就像给宠物起名字一样,给变量起名字也有一些规则:

  1. 名字可以包含字母、数字和下划线(_)

  2. 名字不能以数字开头

  3. 名字不能包含空格

  4. 不能使用Python的关键词(比如print)

好的变量名:

  
student_name = "小红"
  
score = 95
  
is_happy = True
  
favorite_color = "蓝色"
  

不好的变量名:

  
# 这些都是错误的!
  
# 2student = "小明"  # 不能以数字开头
  
# my name = "小红"   # 不能有空格
  
# print = 100        # 不能使用关键词
  

2.3 变量的魔法:可以改变!

变量最神奇的地方是它们可以改变内容,就像魔法盒子可以重新装东西:

  
pocket_money = 10
  
print("我的零花钱有:", pocket_money, "元")
  

  
# 妈妈又给了5元
  
pocket_money = pocket_money + 5
  
print("现在我有:", pocket_money, "元")
  

  
# 买了一支3元的冰淇淋
  
pocket_money = pocket_money - 3
  
print("买完冰淇淋还剩:", pocket_money, "元")
  

2.4 不同类型的变量

Python中的变量可以存放不同类型的数据:

  
# 字符串(文字)
  
favorite_food = "披萨"
  
school_name = "阳光小学"
  

  
# 整数
  
student_count = 30
  
book_pages = 256
  

  
# 小数(浮点数)
  
temperature = 26.5
  
pi = 3.14159
  

  
# 布尔值(对或错)
  
is_sunny = True
  
is_raining = False
  

  
print("我最喜欢吃", favorite_food)
  
print("今天温度是", temperature, "度")
  
print("今天是晴天吗?", is_sunny)
  

第三章:和Python对话——输入与输出

3.1 让Python听懂你的话

到目前为止,我们一直在让Python说话,现在让我们教Python听我们说话!使用input()函数:

  
name = input("请问你叫什么名字?")
  
print("你好,", name, "!很高兴认识你!")
  

  
age = input("你今年几岁了?")
  
print("哇,", age, "岁是个很棒的年纪!")
  

运行这段代码,Python会等待你输入答案,然后根据你的回答做出回应。

3.2 制作一个自我介绍程序

让我们做一个更有趣的程序:

  
print("=== 自我介绍小程序 ===")
  

  
name = input("你的名字是:")
  
age = input("你的年龄是:")
  
hobby = input("你最喜欢做什么:")
  
pet = input("你有什么宠物吗:")
  

  
print("\n--- 自我介绍 ---")
  
print("大家好!我叫" + name)
  
print("我今年" + age + "岁")
  
print("我最喜欢" + hobby)
  
print("我的宠物是" + pet)
  
print("很高兴认识大家!")
  

3.3 数字输入的小技巧

当我们需要输入数字进行计算时,需要特别注意:

  
# 这样会出错!
  
age = input("你几岁了?")
  
next_year_age = age + 1  # 错误!不能把文字和数字相加
  

  
# 正确的做法
  
age = input("你几岁了?")
  
age = int(age)  # 把文字转换成数字
  
next_year_age = age + 1
  
print("明年你就", next_year_age, "岁了!")
  

更简单的写法:

  
age = int(input("你几岁了?"))
  
print("10年后你就", age + 10, "岁了!")
  

3.4 制作一个简单的计算器

  
print("=== 小小计算器 ===")
  

  
num1 = float(input("请输入第一个数字:"))
  
num2 = float(input("请输入第二个数字:"))
  

  
print("\n计算结果:")
  
print(num1, "+", num2, "=", num1 + num2)
  
print(num1, "-", num2, "=", num1 - num2)
  
print(num1, "×", num2, "=", num1 * num2)
  
print(num1, "÷", num2, "=", num1 / num2)
  

第四章:做决定的魔法——条件判断

4.1 如果...那么...

在生活中,我们经常需要做决定:如果今天下雨,那么带伞;如果作业做完了,那么可以玩游戏。Python也可以做这样的决定!

  
weather = input("今天的天气怎么样?(晴天/雨天)")
  

  
if weather == "雨天":
  
    print("记得带伞哦!")
  
    print("穿上雨鞋会更好")
  

注意:

  • if 后面要加冒号 :

  • 要执行的代码需要缩进(按Tab键或4个空格)

  • == 表示"等于"(两个等号)

4.2 如果...否则...

  
score = int(input("你的考试分数是多少?"))
  

  
if score >= 90:
  
    print("太棒了!你得了A!")
  
    print("继续保持!")
  
else:
  
    print("没关系,下次继续努力!")
  
    print("我相信你可以做得更好!")
  

4.3 多重选择

有时候我们需要更多选择:

  
score = int(input("请输入你的分数:"))
  

  
if score >= 90:
  
    print("优秀!等级:A")
  
elif score >= 80:
  
    print("良好!等级:B")
  
elif score >= 70:
  
    print("中等!等级:C")
  
elif score >= 60:
  
    print("及格!等级:D")
  
else:
  
    print("需要加油!等级:F")
  

4.4 制作一个小游戏:猜年龄

  
print("=== 猜年龄游戏 ===")
  
print("我在想一个1到10之间的数字,你能猜到吗?")
  

  
secret_age = 7  # 这是要猜的数字
  
guess = int(input("请输入你的猜测:"))
  

  
if guess == secret_age:
  
    print("哇!你猜对了!真厉害!")
  
elif guess > secret_age:
  
    print("太大了!实际数字更小一些")
  
else:
  
    print("太小了!实际数字更大一些")
  

4.5 组合条件

我们可以用 and(并且)和 or(或者)来组合条件:

  
age = int(input("你几岁了?"))
  
height = float(input("你的身高是多少厘米?"))
  

  
# 过山车的要求:年龄大于8岁 并且 身高超过120厘米
  
if age > 8 and height > 120:
  
    print("你可以玩过山车了!")
  
else:
  
    print("对不起,你还不能玩过山车")
  

  
# 游泳池的规则:带了泳帽 或者 是游泳队成员
  
has_cap = input("你带泳帽了吗?(是/否)")
  
is_member = input("你是游泳队成员吗?(是/否)")
  

  
if has_cap == "是" or is_member == "是":
  
    print("欢迎进入游泳池!")
  
else:
  
    print("请准备好泳帽再来")
  

第五章:重复的魔法——循环

5.1 for循环:数数字

当我们需要重复做某件事时,循环就派上用场了!

  
# 从1数到10
  
for i in range(1, 11):
  
    print(i)
  

  
# 打印5次"我爱Python!"
  
for i in range(5):
  
    print("我爱Python!")
  

range()函数的用法:

  • range(5) 表示 0, 1, 2, 3, 4

  • range(1, 6) 表示 1, 2, 3, 4, 5

  • range(0, 10, 2) 表示 0, 2, 4, 6, 8

5.2 用循环画图案

  
# 画一个三角形
  
for i in range(1, 6):
  
    print("*" * i)
  

  
# 画一个正方形
  
size = 5
  
for i in range(size):
  
    print("* " * size)
  

  
# 画一个倒三角形
  
for i in range(5, 0, -1):
  
    print("*" * i)
  

5.3 while循环:一直做直到...

  
# 倒计时
  
count = 10
  
while count > 0:
  
    print(count)
  
    count = count - 1
  
print("发射!")
  

  
# 累加零花钱
  
total_money = 0
  
day = 1
  

  
while day <= 7:
  
    print("第", day, "天")
  
    money = int(input("今天得到多少零花钱?"))
  
    total_money = total_money + money
  
    day = day + 1
  

  
print("这周总共得到", total_money, "元零花钱")
  

5.4 猜数字游戏(完整版)

  
import random
  

  
print("=== 猜数字游戏 ===")
  
secret_number = random.randint(1, 100)
  
guess_count = 0
  

  
print("我想了一个1到100之间的数字,你能猜到吗?")
  

  
while True:
  
    guess = int(input("请输入你的猜测:"))
  
    guess_count = guess_count + 1
  
    
  
    if guess == secret_number:
  
        print("恭喜你猜对了!")
  
        print("你一共猜了", guess_count, "次")
  
        break
  
    elif guess > secret_number:
  
        print("太大了!再小一点")
  
    else:
  
        print("太小了!再大一点")
  

5.5 嵌套循环:循环中的循环

  
# 九九乘法表
  
for i in range(1, 10):
  
    for j in range(1, i + 1):
  
        print(j, "×", i, "=", i * j, end="  ")
  
    print()  # 换行
  

  
# 画一个由星星组成的矩形
  
rows = 4
  
cols = 6
  

  
for i in range(rows):
  
    for j in range(cols):
  
        print("*", end=" ")
  
    print()  # 每行结束后换行
  

第六章:列表——超级储物架

6.1 什么是列表?

如果变量是一个盒子,那么列表就是一个有很多格子的储物架,每个格子都可以放东西!

  
# 创建一个列表
  
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
  
print(fruits)
  

  
# 我的朋友们
  
friends = ["小明", "小红", "小华", "小李"]
  
print("我的朋友有:", friends)
  

  
# 考试分数
  
scores = [85, 92, 78, 96, 88]
  
print("这次考试的分数:", scores)
  

6.2 访问列表中的元素

列表中的每个位置都有一个编号,从0开始:

  
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
  

  
print("第一个水果是:", fruits[0])  # 苹果
  
print("第二个水果是:", fruits[1])  # 香蕉
  
print("最后一个水果是:", fruits[-1])  # 葡萄
  

  
# 修改列表中的元素
  
fruits[1] = "芒果"
  
print("现在的水果列表:", fruits)
  

6.3 列表的魔法操作

  
# 添加元素
  
pets = ["小狗", "小猫"]
  
pets.append("小兔子")  # 在末尾添加
  
print(pets)
  

  
# 插入元素
  
pets.insert(1, "小鸟")  # 在位置1插入
  
print(pets)
  

  
# 删除元素
  
pets.remove("小猫")  # 删除指定元素
  
print(pets)
  

  
# 列表长度
  
print("我有", len(pets), "只宠物")
  

  
# 检查元素是否在列表中
  
if "小狗" in pets:
  
    print("我有一只小狗!")
  

6.4 用循环遍历列表

  
# 打印所有水果
  
fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"]
  

  
print("我喜欢的水果有:")
  
for fruit in fruits:
  
    print("- " + fruit)
  

  
# 计算总分和平均分
  
scores = [85, 92, 78, 96, 88]
  
total = 0
  

  
for score in scores:
  
    total = total + score
  

  
average = total / len(scores)
  
print("总分:", total)
  
print("平均分:", average)
  

6.5 列表小游戏:购物清单

  
print("=== 购物清单管理器 ===")
  
shopping_list = []
  

  
while True:
  
    print("\n当前购物清单:", shopping_list)
  
    print("1. 添加物品")
  
    print("2. 删除物品")
  
    print("3. 查看清单")
  
    print("4. 退出")
  
    
  
    choice = input("请选择操作(1-4):")
  
    
  
    if choice == "1":
  
        item = input("要添加什么物品?")
  
        shopping_list.append(item)
  
        print(item, "已添加到购物清单")
  
    
  
    elif choice == "2":
  
        if len(shopping_list) == 0:
  
            print("购物清单是空的!")
  
        else:
  
            item = input("要删除什么物品?")
  
            if item in shopping_list:
  
                shopping_list.remove(item)
  
                print(item, "已从购物清单删除")
  
            else:
  
                print("清单中没有这个物品")
  
    
  
    elif choice == "3":
  
        if len(shopping_list) == 0:
  
            print("购物清单是空的!")
  
        else:
  
            print("需要购买的物品:")
  
            for i, item in enumerate(shopping_list, 1):
  
                print(f"{i}. {item}")
  
    
  
    elif choice == "4":
  
        print("再见!")
  
        break
  
    
  
    else:
  
        print("无效的选择,请重试")
  

第七章:函数——你的编程助手

7.1 什么是函数?

函数就像是一个小助手,你告诉它做什么,它就会帮你完成。我们已经用过一些函数了,比如print()input()。现在让我们学习创建自己的函数!

  
# 定义一个打招呼的函数
  
def say_hello():
  
    print("你好!")
  
    print("欢迎来到Python世界!")
  

  
# 调用函数
  
say_hello()
  
say_hello()  # 可以多次调用
  

7.2 带参数的函数

函数可以接收信息(参数),根据不同的信息做不同的事:

  
def greet(name):
  
    print("你好," + name + "!")
  
    print("很高兴见到你!")
  

  
# 调用函数时提供参数
  
greet("小明")
  
greet("老师")
  

  
# 多个参数的函数
  
def introduce(name, age, hobby):
  
    print(f"我叫{name}")
  
    print(f"我今年{age}岁")
  
    print(f"我喜欢{hobby}")
  

  
introduce("小红", 10, "画画")
  

7.3 返回值的函数

函数不仅可以做事,还可以计算并返回结果:

  
def add(a, b):
  
    result = a + b
  
    return result
  

  
# 使用函数的返回值
  
sum = add(5, 3)
  
print("5 + 3 =", sum)
  

  
# 计算矩形面积的函数
  
def rectangle_area(length, width):
  
    area = length * width
  
    return area
  

  
my_area = rectangle_area(10, 5)
  
print("矩形的面积是:", my_area)
  

7.4 实用的函数例子

  
# 判断是否及格
  
def is_pass(score):
  
    if score >= 60:
  
        return True
  
    else:
  
        return False
  

  
# 计算平均分
  
def calculate_average(scores):
  
    total = sum(scores)
  
    average = total / len(scores)
  
    return average
  

  
# 生成问候语
  
def make_greeting(time_of_day):
  
    if time_of_day == "早上":
  
        return "早上好!祝你有美好的一天!"
  
    elif time_of_day == "下午":
  
        return "下午好!别忘了喝水哦!"
  
    elif time_of_day == "晚上":
  
        return "晚上好!今天过得怎么样?"
  
    else:
  
        return "你好!"
  

  
# 使用这些函数
  
print(is_pass(75))
  
print(calculate_average([80, 90, 85, 92]))
  
print(make_greeting("早上"))
  

7.5 制作一个简单的游戏菜单

  
def show_menu():
  
    print("\n=== 游戏菜单 ===")
  
    print("1. 猜数字")
  
    print("2. 石头剪刀布")
  
    print("3. 数学测验")
  
    print("4. 退出游戏")
  

  
def guess_number_game():
  
    import random
  
    number = random.randint(1, 10)
  
    guess = int(input("猜一个1到10的数字:"))
  
    
  
    if guess == number:
  
        print("猜对了!")
  
    else:
  
        print(f"错了,正确答案是{number}")
  

  
def rock_paper_scissors():
  
    import random
  
    choices = ["石头", "剪刀", "布"]
  
    computer_choice = random.choice(choices)
  
    
  
    player_choice = input("请出拳(石头/剪刀/布):")
  
    print(f"电脑出了:{computer_choice}")
  
    
  
    if player_choice == computer_choice:
  
        print("平局!")
  
    elif (player_choice == "石头" and computer_choice == "剪刀") or \
  
         (player_choice == "剪刀" and computer_choice == "布") or \
  
         (player_choice == "布" and computer_choice == "石头"):
  
        print("你赢了!")
  
    else:
  
        print("你输了!")
  

  
def math_quiz():
  
    import random
  
    num1 = random.randint(1, 20)
  
    num2 = random.randint(1, 20)
  
    
  
    answer = int(input(f"{num1} + {num2} = "))
  
    
  
    if answer == num1 + num2:
  
        print("答对了!真棒!")
  
    else:
  
        print(f"答错了,正确答案是 {num1 + num2}")
  

  
# 主程序
  
while True:
  
    show_menu()
  
    choice = input("请选择(1-4):")
  
    
  
    if choice == "1":
  
        guess_number_game()
  
    elif choice == "2":
  
        rock_paper_scissors()
  
    elif choice == "3":
  
        math_quiz()
  
    elif choice == "4":
  
        print("谢谢游玩,再见!")
  
        break
  
    else:
  
        print("无效选择,请重试")
  

第八章:字符串的魔法

8.1 字符串是什么?

字符串就是文字的集合,可以是一个字母、一个词或一句话。在Python中,我们用引号把文字包起来就成了字符串。

  
# 不同的字符串
  
name = "小明"
  
sentence = "我喜欢编程!"
  
story = "从前有座山,山里有座庙..."
  

  
# 单引号和双引号都可以
  
msg1 = "你好"
  
msg2 = '你好'
  
print(msg1 == msg2)  # True,它们是一样的
  

  
# 多行字符串
  
poem = """
  
床前明月光,
  
疑是地上霜。
  
举头望明月,
  
低头思故乡。
  
"""
  
print(poem)
  

8.2 字符串的操作

  
# 字符串拼接
  
first_name = "张"
  
last_name = "小明"
  
full_name = first_name + last_name
  
print(full_name)
  

  
# 重复字符串
  
laugh = "哈"
  
big_laugh = laugh * 5
  
print(big_laugh)  # 哈哈哈哈哈
  

  
# 字符串长度
  
message = "Hello Python"
  
print(len(message))  # 12
  

  
# 访问字符串中的字符
  
word = "Python"
  
print(word[0])  # P
  
print(word[1])  # y
  
print(word[-1]) # n(最后一个)
  

8.3 字符串的方法

  
# 大小写转换
  
text = "Hello World"
  
print(text.upper())  # HELLO WORLD
  
print(text.lower())  # hello world
  

  
# 查找和替换
  
sentence = "我喜欢苹果,苹果很好吃"
  
print(sentence.count("苹果"))  # 2
  
print(sentence.replace("苹果", "香蕉"))
  

  
# 分割字符串
  
fruits = "苹果,香蕉,橙子,葡萄"
  
fruit_list = fruits.split(",")
  
print(fruit_list)  # ['苹果', '香蕉', '橙子', '葡萄']
  

  
# 去除空格
  
name = "  小明  "
  
print(name.strip())  # "小明"
  

8.4 格式化字符串

  
# 使用 f-string(推荐)
  
name = "小红"
  
age = 10
  
height = 145.5
  

  
introduction = f"我叫{name},今年{age}岁,身高{height}厘米"
  
print(introduction)
  

  
# 在f-string中进行计算
  
price = 15
  
quantity = 3
  
print(f"单价{price}元,买{quantity}个,总共{price * quantity}元")
  

  
# 格式化数字
  
pi = 3.14159265
  
print(f"圆周率约等于{pi:.2f}")  # 保留2位小数
  

8.5 字符串小游戏:词语接龙

  
print("=== 词语接龙游戏 ===")
  
print("规则:下一个词的第一个字必须是上一个词的最后一个字")
  

  
words = ["苹果"]
  
print(f"第一个词是:{words[0]}")
  

  
while True:
  
    last_word = words[-1]
  
    last_char = last_word[-1]
  
    
  
    print(f"\n当前词语:{last_word}")
  
    print(f"请输入一个以'{last_char}'开头的词语")
  
    
  
    new_word = input("你的词语:")
  
    
  
    if new_word == "退出":
  
        break
  
    
  
    if len(new_word) < 2:
  
        print("词语至少要有两个字!")
  
        continue
  
    
  
    if new_word[0] != last_char:
  
        print(f"错误!必须以'{last_char}'开头")
  
        continue
  
    
  
    if new_word in words:
  
        print("这个词已经用过了!")
  
        continue
  
    
  
    words.append(new_word)
  
    print("好词!继续!")
  

  
print(f"\n游戏结束!你一共接了{len(words)}个词")
  
print("所有词语:", " -> ".join(words))
  

第九章:字典——超级通讯录

9.1 什么是字典?

如果列表像是一个储物架,那字典就像是一个通讯录。在通讯录中,每个人的名字对应着他的电话号码。在Python字典中,每个"键"对应着一个"值"。

  
# 创建一个字典
  
student = {
  
    "姓名": "小明",
  
    "年龄": 10,
  
    "年级": "四年级",
  
    "爱好": "踢足球"
  
}
  

  
print(student)
  
print(student["姓名"])  # 小明
  
print(student["爱好"])  # 踢足球
  

9.2 字典的操作

  
# 创建一个宠物信息字典
  
pet = {
  
    "名字": "毛毛",
  
    "种类": "小狗",
  
    "年龄": 3,
  
    "颜色": "棕色"
  
}
  

  
# 修改值
  
pet["年龄"] = 4
  
print(f"{pet['名字']}现在{pet['年龄']}岁了")
  

  
# 添加新的键值对
  
pet["最爱的食物"] = "骨头"
  
print(pet)
  

  
# 删除键值对
  
del pet["颜色"]
  

  
# 检查键是否存在
  
if "名字" in pet:
  
    print(f"宠物的名字是{pet['名字']}")
  

9.3 遍历字典

  
# 学生成绩单
  
scores = {
  
    "语文": 92,
  
    "数学": 88,
  
    "英语": 95,
  
    "科学": 90,
  
    "体育": 98
  
}
  

  
# 遍历所有科目和分数
  
print("成绩单:")
  
for subject, score in scores.items():
  
    print(f"{subject}: {score}分")
  

  
# 计算总分和平均分
  
total = sum(scores.values())
  
average = total / len(scores)
  
print(f"\n总分:{total}分")
  
print(f"平均分:{average:.1f}分")
  

  
# 找出最高分的科目
  
max_score = max(scores.values())
  
for subject, score in scores.items():
  
    if score == max_score:
  
        print(f"最擅长的科目是{subject},得了{score}分!")
  

9.4 嵌套字典

  
# 班级通讯录
  
class_contacts = {
  
    "小明": {
  
        "电话": "13812345678",
  
        "邮箱": "xiaoming@email.com",
  
        "地址": "阳光小区1号楼"
  
    },
  
    "小红": {
  
        "电话": "13887654321",
  
        "邮箱": "xiaohong@email.com",
  
        "地址": "花园小区2号楼"
  
    },
  
    "小华": {
  
        "电话": "13856781234",
  
        "邮箱": "xiaohua@email.com",
  
        "地址": "幸福小区3号楼"
  
    }
  
}
  

  
# 查找某人的信息
  
name = input("要查找谁的信息?")
  
if name in class_contacts:
  
    info = class_contacts[name]
  
    print(f"\n{name}的信息:")
  
    for key, value in info.items():
  
        print(f"{key}: {value}")
  
else:
  
    print("没有找到这个人的信息")
  

9.5 字典应用:简单的单词本

  
print("=== 英语单词本 ===")
  

  
word_book = {
  
    "apple": "苹果",
  
    "banana": "香蕉",
  
    "cat": "猫",
  
    "dog": "狗",
  
    "elephant": "大象",
  
    "flower": "花",
  
    "good": "好的",
  
    "happy": "快乐的",
  
    "ice cream": "冰淇淋",
  
    "juice": "果汁"
  
}
  

  
while True:
  
    print("\n1. 查单词")
  
    print("2. 添加新单词")
  
    print("3. 显示所有单词")
  
    print("4. 单词测试")
  
    print("5. 退出")
  
    
  
    choice = input("请选择(1-5):")
  
    
  
    if choice == "1":
  
        word = input("请输入要查的英文单词:").lower()
  
        if word in word_book:
  
            print(f"{word} 的意思是:{word_book[word]}")
  
        else:
  
            print("单词本里还没有这个单词")
  
    
  
    elif choice == "2":
  
        english = input("请输入英文单词:").lower()
  
        chinese = input("请输入中文意思:")
  
        word_book[english] = chinese
  
        print("单词已添加!")
  
    
  
    elif choice == "3":
  
        print("\n单词本中的所有单词:")
  
        for eng, chi in word_book.items():
  
            print(f"{eng} - {chi}")
  
    
  
    elif choice == "4":
  
        import random
  
        test_word = random.choice(list(word_book.keys()))
  
        answer = input(f"{test_word} 的意思是什么?")
  
        
  
        if answer == word_book[test_word]:
  
            print("答对了!真棒!")
  
        else:
  
            print(f"答错了,{test_word} 的意思是 {word_book[test_word]}")
  
    
  
    elif choice == "5":
  
        print("再见!继续努力学习哦!")
  
        break
  

第十章:文件操作——保存你的作品

10.1 写入文件

到目前为止,我们的程序运行结束后,所有数据都会消失。现在让我们学习如何把数据保存到文件中!

  
# 写入文件
  
with open("my_diary.txt", "w", encoding="utf-8") as file:
  
    file.write("今天是个好天气!\n")
  
    file.write("我学会了Python文件操作。\n")
  
    file.write("感觉自己越来越厉害了!")
  

  
print("日记已保存!")
  

  
# 写入多行
  
diary_lines = [
  
    "2024年10月20日 星期日\n",
  
    "今天我和朋友一起去公园玩。\n",
  
    "我们看到了很多漂亮的花。\n",
  
    "还喂了池塘里的小鱼。\n",
  
    "真是开心的一天!"
  
]
  

  
with open("my_diary2.txt", "w", encoding="utf-8") as file:
  
    file.writelines(diary_lines)
  

10.2 读取文件

  
# 读取整个文件
  
with open("my_diary.txt", "r", encoding="utf-8") as file:
  
    content = file.read()
  
    print("日记内容:")
  
    print(content)
  

  
# 逐行读取
  
print("\n逐行读取:")
  
with open("my_diary.txt", "r", encoding="utf-8") as file:
  
    for line in file:
  
        print(">>", line.strip())  # strip()去除行尾的换行符
  

10.3 追加内容

  
# 追加模式 - 在文件末尾添加内容
  
with open("my_diary.txt", "a", encoding="utf-8") as file:
  
    file.write("\n\n新的一天:\n")
  
    file.write("今天又学会了新知识!\n")
  

  
print("新内容已追加到日记中!")
  

10.4 成绩管理系统

  
import json
  

  
def save_scores(scores_dict):
  
    """保存成绩到文件"""
  
    with open("scores.json", "w", encoding="utf-8") as file:
  
        json.dump(scores_dict, file, ensure_ascii=False, indent=2)
  
    print("成绩已保存!")
  

  
def load_scores():
  
    """从文件读取成绩"""
  
    try:
  
        with open("scores.json", "r", encoding="utf-8") as file:
  
            return json.load(file)
  
    except FileNotFoundError:
  
        return {}
  

  
def main():
  
    print("=== 成绩管理系统 ===")
  
    scores = load_scores()
  
    
  
    while True:
  
        print("\n1. 添加成绩")
  
        print("2. 查看成绩")
  
        print("3. 查看所有成绩")
  
        print("4. 退出")
  
        
  
        choice = input("请选择(1-4):")
  
        
  
        if choice == "1":
  
            name = input("学生姓名:")
  
            subject = input("科目:")
  
            score = int(input("分数:"))
  
            
  
            if name not in scores:
  
                scores[name] = {}
  
            scores[name][subject] = score
  
            save_scores(scores)
  
            
  
        elif choice == "2":
  
            name = input("要查看谁的成绩?")
  
            if name in scores:
  
                print(f"\n{name}的成绩:")
  
                for subject, score in scores[name].items():
  
                    print(f"{subject}: {score}分")
  
            else:
  
                print("没有找到这个学生的成绩")
  
        
  
        elif choice == "3":
  
            if scores:
  
                print("\n所有学生成绩:")
  
                for name, subjects in scores.items():
  
                    print(f"\n{name}:")
  
                    for subject, score in subjects.items():
  
                        print(f"  {subject}: {score}分")
  
            else:
  
                print("还没有任何成绩记录")
  
        
  
        elif choice == "4":
  
            print("再见!")
  
            break
  

  
if __name__ == "__main__":
  
    main()
  

10.5 制作一个简单的通讯录

  
def save_contacts(contacts):
  
    """保存通讯录到文件"""
  
    with open("contacts.txt", "w", encoding="utf-8") as file:
  
        for name, phone in contacts.items():
  
            file.write(f"{name},{phone}\n")
  

  
def load_contacts():
  
    """从文件加载通讯录"""
  
    contacts = {}
  
    try:
  
        with open("contacts.txt", "r", encoding="utf-8") as file:
  
            for line in file:
  
                line = line.strip()
  
                if line:
  
                    name, phone = line.split(",")
  
                    contacts[name] = phone
  
    except FileNotFoundError:
  
        pass
  
    return contacts
  

  
print("=== 我的通讯录 ===")
  
contacts = load_contacts()
  

  
while True:
  
    print("\n1. 添加联系人")
  
    print("2. 查找联系人")
  
    print("3. 显示所有联系人")
  
    print("4. 删除联系人")
  
    print("5. 退出")
  
    
  
    choice = input("请选择(1-5):")
  
    
  
    if choice == "1":
  
        name = input("姓名:")
  
        phone = input("电话:")
  
        contacts[name] = phone
  
        save_contacts(contacts)
  
        print("联系人已添加!")
  
    
  
    elif choice == "2":
  
        name = input("要查找谁?")
  
        if name in contacts:
  
            print(f"{name}的电话是:{contacts[name]}")
  
        else:
  
            print("没有找到这个联系人")
  
    
  
    elif choice == "3":
  
        if contacts:
  
            print("\n所有联系人:")
  
            for name, phone in contacts.items():
  
                print(f"{name}: {phone}")
  
        else:
  
            print("通讯录是空的")
  
    
  
    elif choice == "4":
  
        name = input("要删除谁?")
  
        if name in contacts:
  
            del contacts[name]
  
            save_contacts(contacts)
  
            print("联系人已删除!")
  
        else:
  
            print("没有找到这个联系人")
  
    
  
    elif choice == "5":
  
        print("再见!")
  
        break
  

第十一章:图形编程——让程序动起来

11.1 认识Turtle图形库

Turtle(海龟)是Python内置的图形库,我们可以想象有一只小海龟在屏幕上爬行,它爬过的地方会留下轨迹,这样就能画出各种图形了!

  
import turtle
  

  
# 创建画布和海龟
  
screen = turtle.Screen()
  
screen.title("我的第一个图形程序")
  
t = turtle.Turtle()
  

  
# 画一个正方形
  
for i in range(4):
  
    t.forward(100)  # 前进100步
  
    t.right(90)     # 右转90度
  

  
# 保持窗口打开
  
turtle.done()
  

11.2 基本绘图命令

  
import turtle
  

  
t = turtle.Turtle()
  
t.speed(5)  # 设置速度(1-10,10最快)
  

  
# 移动命令
  
t.forward(100)    # 前进100步
  
t.backward(50)    # 后退50步
  
t.right(90)       # 右转90度
  
t.left(45)        # 左转45度
  

  
# 画笔控制
  
t.penup()         # 抬起画笔(移动时不画线)
  
t.goto(0, 0)      # 移动到坐标(0,0)
  
t.pendown()       # 放下画笔
  

  
# 颜色和粗细
  
t.pencolor("red")     # 设置画笔颜色
  
t.pensize(3)          # 设置画笔粗细
  
t.fillcolor("yellow") # 设置填充颜色
  

  
# 画一个填充的圆
  
t.begin_fill()
  
t.circle(50)      # 画半径为50的圆
  
t.end_fill()
  

  
turtle.done()
  

11.3 画出美丽的图案

  
import turtle
  

  
# 画彩虹色的花朵
  
def draw_flower():
  
    t = turtle.Turtle()
  
    t.speed(10)
  
    colors = ["red", "orange", "yellow", "green", "blue", "purple"]
  
    
  
    for i in range(36):
  
        t.color(colors[i % 6])
  
        t.circle(100)
  
        t.right(10)
  
    
  
    turtle.done()
  

  
# 画螺旋图案
  
def draw_spiral():
  
    t = turtle.Turtle()
  
    t.speed(10)
  
    colors = ["red", "blue", "green", "yellow"]
  
    
  
    for i in range(100):
  
        t.color(colors[i % 4])
  
        t.forward(i * 2)
  
        t.right(91)
  
    
  
    turtle.done()
  

  
# 画五角星
  
def draw_star():
  
    t = turtle.Turtle()
  
    t.color("gold")
  
    t.begin_fill()
  
    
  
    for i in range(5):
  
        t.forward(100)
  
        t.right(144)
  
    
  
    t.end_fill()
  
    turtle.done()
  

  
# 选择要画的图案
  
print("选择要画的图案:")
  
print("1. 彩虹花朵")
  
print("2. 螺旋图案")
  
print("3. 五角星")
  

  
choice = input("请选择(1-3):")
  

  
if choice == "1":
  
    draw_flower()
  
elif choice == "2":
  
    draw_spiral()
  
elif choice == "3":
  
    draw_star()
  

11.4 交互式绘图

  
import turtle
  

  
# 创建画布和海龟
  
screen = turtle.Screen()
  
screen.title("键盘控制画图")
  
screen.bgcolor("lightblue")
  

  
t = turtle.Turtle()
  
t.speed(0)
  
t.width(2)
  

  
# 定义移动函数
  
def move_up():
  
    t.setheading(90)  # 朝上
  
    t.forward(10)
  

  
def move_down():
  
    t.setheading(270)  # 朝下
  
    t.forward(10)
  

  
def move_left():
  
    t.setheading(180)  # 朝左
  
    t.forward(10)
  

  
def move_right():
  
    t.setheading(0)   # 朝右
  
    t.forward(10)
  

  
def pen_up():
  
    t.penup()
  

  
def pen_down():
  
    t.pendown()
  

  
def change_color():
  
    colors = ["red", "blue", "green", "yellow", "purple", "orange"]
  
    import random
  
    t.color(random.choice(colors))
  

  
def clear_screen():
  
    t.clear()
  
    t.penup()
  
    t.home()
  
    t.pendown()
  

  
# 绑定按键
  
screen.onkey(move_up, "Up")
  
screen.onkey(move_down, "Down")
  
screen.onkey(move_left, "Left")
  
screen.onkey(move_right, "Right")
  
screen.onkey(pen_up, "u")
  
screen.onkey(pen_down, "d")
  
screen.onkey(change_color, "c")
  
screen.onkey(clear_screen, "space")
  

  
# 显示说明
  
t.penup()
  
t.goto(-200, 200)
  
t.write("使用方向键移动,U抬笔,D落笔,C换颜色,空格清屏", 
  
        font=("Arial", 12, "normal"))
  
t.goto(0, 0)
  
t.pendown()
  

  
# 监听按键
  
screen.listen()
  
screen.mainloop()
  

11.5 小海龟赛跑游戏

  
import turtle
  
import random
  

  
# 设置屏幕
  
screen = turtle.Screen()
  
screen.title("小海龟赛跑")
  
screen.bgcolor("lightgreen")
  
screen.setup(width=800, height=600)
  

  
# 画起跑线
  
line = turtle.Turtle()
  
line.hideturtle()
  
line.penup()
  
line.goto(-300, 200)
  
line.pendown()
  
line.goto(-300, -200)
  

  
# 画终点线
  
line.penup()
  
line.goto(300, 200)
  
line.pendown()
  
line.goto(300, -200)
  

  
# 创建参赛海龟
  
colors = ["red", "blue", "green", "yellow", "purple"]
  
turtles = []
  
y_positions = [100, 50, 0, -50, -100]
  

  
for i in range(5):
  
    racer = turtle.Turtle()
  
    racer.shape("turtle")
  
    racer.color(colors[i])
  
    racer.penup()
  
    racer.goto(-320, y_positions[i])
  
    turtles.append(racer)
  

  
# 让用户下注
  
user_bet = screen.textinput("下注", "哪只海龟会赢?输入颜色:")
  

  
# 开始比赛
  
race_on = True
  
winner = None
  

  
while race_on:
  
    for racer in turtles:
  
        if racer.xcor() > 280:
  
            race_on = False
  
            winner = racer.pencolor()
  
            break
  
        
  
        # 随机移动距离
  
        distance = random.randint(1, 10)
  
        racer.forward(distance)
  

  
# 宣布结果
  
result = turtle.Turtle()
  
result.hideturtle()
  
result.penup()
  
result.goto(0, 250)
  

  
if winner == user_bet:
  
    result.write(f"{winner}海龟赢了!你猜对了!", 
  
                 align="center", font=("Arial", 20, "bold"))
  
else:
  
    result.write(f"{winner}海龟赢了!你猜的是{user_bet}", 
  
                 align="center", font=("Arial", 20, "bold"))
  

  
screen.exitonclick()
  

第十二章:面向对象编程——创建你的游戏角色

12.1 什么是类和对象?

想象一下,"类"就像是一个模具,而"对象"就是用这个模具制作出来的具体东西。比如,"汽车"是一个类,而你家的那辆红色小汽车就是一个对象。

  
# 创建一个宠物类
  
class Pet:
  
    def __init__(self, name, age):
  
        self.name = name
  
        self.age = age
  
    
  
    def introduce(self):
  
        print(f"我是{self.name},今年{self.age}岁了!")
  
    
  
    def make_sound(self):
  
        print("宠物发出了声音")
  

  
# 创建宠物对象
  
my_pet = Pet("小白", 3)
  
my_pet.introduce()
  
my_pet.make_sound()
  

  
# 创建更多宠物
  
pet2 = Pet("花花", 2)
  
pet2.introduce()
  

12.2 继承——创建不同种类的宠物

  
# 基础宠物类
  
class Pet:
  
    def __init__(self, name, age):
  
        self.name = name
  
        self.age = age
  
        self.happiness = 50
  
        self.hunger = 50
  
    
  
    def feed(self):
  
        self.hunger -= 10
  
        self.happiness += 5
  
        print(f"{self.name}吃饱了!饥饿度-10,快乐度+5")
  
    
  
    def play(self):
  
        self.happiness += 10
  
        self.hunger += 5
  
        print(f"{self.name}玩得很开心!快乐度+10,饥饿度+5")
  
    
  
    def status(self):
  
        print(f"\n{self.name}的状态:")
  
        print(f"年龄:{self.age}岁")
  
        print(f"快乐度:{self.happiness}")
  
        print(f"饥饿度:{self.hunger}")
  

  
# 狗类(继承自Pet)
  
class Dog(Pet):
  
    def make_sound(self):
  
        print(f"{self.name}:汪汪汪!")
  
    
  
    def fetch(self):
  
        print(f"{self.name}叼回了球!")
  
        self.happiness += 15
  

  
# 猫类(继承自Pet)
  
class Cat(Pet):
  
    def make_sound(self):
  
        print(f"{self.name}:喵喵喵~")
  
    
  
    def scratch(self):
  
        print(f"{self.name}在磨爪子")
  
        self.happiness += 10
  

  
# 创建不同的宠物
  
my_dog = Dog("旺财", 4)
  
my_cat = Cat("咪咪", 2)
  

  
# 互动
  
my_dog.make_sound()
  
my_dog.feed()
  
my_dog.fetch()
  
my_dog.status()
  

  
print("\n" + "="*30 + "\n")
  

  
my_cat.make_sound()
  
my_cat.play()
  
my_cat.scratch()
  
my_cat.status()
  

12.3 创建一个学生类

  
class Student:
  
    def __init__(self, name, grade):
  
        self.name = name
  
        self.grade = grade
  
        self.scores = {}
  
        self.homework_done = []
  
    
  
    def add_score(self, subject, score):
  
        self.scores[subject] = score
  
        print(f"{self.name}的{subject}成绩已记录:{score}分")
  
    
  
    def do_homework(self, subject):
  
        self.homework_done.append(subject)
  
        print(f"{self.name}完成了{subject}作业!")
  
    
  
    def get_average_score(self):
  
        if not self.scores:
  
            return 0
  
        total = sum(self.scores.values())
  
        average = total / len(self.scores)
  
        return average
  
    
  
    def report_card(self):
  
        print(f"\n===== {self.name}的成绩单 =====")
  
        print(f"年级:{self.grade}")
  
        print("\n各科成绩:")
  
        for subject, score in self.scores.items():
  
            print(f"{subject}: {score}分")
  
        print(f"\n平均分:{self.get_average_score():.1f}分")
  
        print(f"已完成的作业:{', '.join(self.homework_done)}")
  

  
# 创建学生对象
  
student1 = Student("小明", "五年级")
  
student1.add_score("语文", 92)
  
student1.add_score("数学", 88)
  
student1.add_score("英语", 95)
  
student1.do_homework("语文")
  
student1.do_homework("数学")
  
student1.report_card()
  

12.4 创建一个简单的游戏角色系统

  
import random
  

  
class GameCharacter:
  
    def __init__(self, name, character_type):
  
        self.name = name
  
        self.type = character_type
  
        self.level = 1
  
        self.hp = 100
  
        self.max_hp = 100
  
        self.attack_power = 10
  
        self.defense = 5
  
        self.exp = 0
  
    
  
    def attack(self, enemy):
  
        damage = self.attack_power + random.randint(-3, 3)
  
        actual_damage = max(1, damage - enemy.defense)
  
        enemy.hp -= actual_damage
  
        print(f"{self.name}攻击了{enemy.name},造成{actual_damage}点伤害!")
  
        
  
        if enemy.hp <= 0:
  
            enemy.hp = 0
  
            print(f"{enemy.name}被打败了!")
  
            self.gain_exp(50)
  
    
  
    def heal(self, amount):
  
        old_hp = self.hp
  
        self.hp = min(self.max_hp, self.hp + amount)
  
        healed = self.hp - old_hp
  
        print(f"{self.name}恢复了{healed}点生命值!当前HP: {self.hp}/{self.max_hp}")
  
    
  
    def gain_exp(self, amount):
  
        self.exp += amount
  
        print(f"{self.name}获得了{amount}点经验值!")
  
        
  
        # 检查是否升级
  
        if self.exp >= self.level * 100:
  
            self.level_up()
  
    
  
    def level_up(self):
  
        self.level += 1
  
        self.max_hp += 20
  
        self.hp = self.max_hp
  
        self.attack_power += 5
  
        self.defense += 2
  
        print(f"\n🎉 {self.name}升级了!现在是{self.level}级!")
  
        print(f"HP: {self.max_hp}, 攻击力: {self.attack_power}, 防御力: {self.defense}")
  
    
  
    def show_status(self):
  
        print(f"\n{self.name} ({self.type})")
  
        print(f"等级: {self.level}")
  
        print(f"HP: {self.hp}/{self.max_hp}")
  
        print(f"攻击力: {self.attack_power}")
  
        print(f"防御力: {self.defense}")
  
        print(f"经验值: {self.exp}")
  

  
# 创建不同类型的角色
  
class Warrior(GameCharacter):
  
    def __init__(self, name):
  
        super().__init__(name, "战士")
  
        self.attack_power = 15
  
        self.defense = 8
  
        self.max_hp = 120
  
        self.hp = 120
  
    
  
    def power_strike(self, enemy):
  
        print(f"{self.name}使用了力量打击!")
  
        original_attack = self.attack_power
  
        self.attack_power *= 2
  
        self.attack(enemy)
  
        self.attack_power = original_attack
  

  
class Mage(GameCharacter):
  
    def __init__(self, name):
  
        super().__init__(name, "法师")
  
        self.attack_power = 20
  
        self.defense = 3
  
        self.max_hp = 80
  
        self.hp = 80
  
        self.mana = 50
  
    
  
    def fireball(self, enemy):
  
        if self.mana >= 10:
  
            print(f"{self.name}发射了火球术!")
  
            damage = 30
  
            enemy.hp -= damage
  
            self.mana -= 10
  
            print(f"造成{damage}点魔法伤害!剩余魔力: {self.mana}")
  
            
  
            if enemy.hp <= 0:
  
                enemy.hp = 0
  
                print(f"{enemy.name}被打败了!")
  
                self.gain_exp(50)
  
        else:
  
            print(f"{self.name}魔力不足!")
  

  
# 游戏演示
  
print("=== 角色战斗演示 ===")
  

  
# 创建角色
  
hero = Warrior("勇者")
  
enemy = GameCharacter("史莱姆", "怪物")
  

  
# 显示初始状态
  
hero.show_status()
  
enemy.show_status()
  

  
# 战斗
  
print("\n--- 战斗开始!---")
  
while hero.hp > 0 and enemy.hp > 0:
  
    print(f"\n{hero.name}的回合:")
  
    action = input("选择行动:1.普通攻击 2.力量打击 3.查看状态: ")
  
    
  
    if action == "1":
  
        hero.attack(enemy)
  
    elif action == "2":
  
        hero.power_strike(enemy)
  
    elif action == "3":
  
        hero.show_status()
  
        continue
  
    
  
    # 敌人反击
  
    if enemy.hp > 0:
  
        print(f"\n{enemy.name}的回合:")
  
        enemy.attack(hero)
  

  
# 战斗结果
  
if hero.hp > 0:
  
    print("\n🎊 你赢了!")
  
else:
  
    print("\n💀 游戏结束...")
  

12.5 创建一个虚拟宠物游戏

  
import time
  
import random
  

  
class VirtualPet:
  
    def __init__(self, name, pet_type):
  
        self.name = name
  
        self.type = pet_type
  
        self.hunger = 50
  
        self.happiness = 50
  
        self.health = 100
  
        self.age = 0
  
        self.is_alive = True
  
    
  
    def feed(self):
  
        if self.hunger <= 0:
  
            print(f"{self.name}不饿,不想吃东西")
  
        else:
  
            foods = ["🍎苹果", "🍖肉骨头", "🐟小鱼", "🥕胡萝卜"]
  
            food = random.choice(foods)
  
            self.hunger = max(0, self.hunger - 20)
  
            self.happiness += 10
  
            print(f"{self.name}吃了{food},真好吃!")
  
    
  
    def play(self):
  
        games = ["接飞盘", "追尾巴", "捉迷藏", "玩球"]
  
        game = random.choice(games)
  
        self.happiness = min(100, self.happiness + 20)
  
        self.hunger += 10
  
        self.health -= 5
  
        print(f"{self.name}玩了{game},好开心!")
  
    
  
    def sleep(self):
  
        print(f"{self.name}睡觉中...Zzz...")
  
        self.health = min(100, self.health + 20)
  
        self.hunger += 15
  
        self.happiness += 5
  
        print(f"{self.name}睡醒了,精神满满!")
  
    
  
    def check_status(self):
  
        # 检查宠物状态并更新
  
        if self.hunger >= 100:
  
            self.health -= 20
  
            print(f"⚠️ {self.name}太饿了,健康值下降!")
  
        
  
        if self.happiness <= 0:
  
            self.health -= 10
  
            print(f"⚠️ {self.name}很不开心,健康值下降!")
  
        
  
        if self.health <= 0:
  
            self.is_alive = False
  
            print(f"😢 {self.name}生病了,需要好好照顾...")
  
    
  
    def show_status(self):
  
        print(f"\n===== {self.name}的状态 =====")
  
        print(f"类型:{self.type}")
  
        print(f"年龄:{self.age}天")
  
        print(f"饥饿度:{'🟥' * (self.hunger // 10)}{'⬜' * (10 - self.hunger // 10)} {self.hunger}/100")
  
        print(f"快乐度:{'🟦' * (self.happiness // 10)}{'⬜' * (10 - self.happiness // 10)} {self.happiness}/100")
  
        print(f"健康度:{'🟩' * (self.health // 10)}{'⬜' * (10 - self.health // 10)} {self.health}/100")
  
        
  
        # 显示宠物心情
  
        if self.happiness >= 80:
  
            print(f"心情:😄 非常开心")
  
        elif self.happiness >= 50:
  
            print(f"心情:🙂 还不错")
  
        elif self.happiness >= 20:
  
            print(f"心情:😐 一般般")
  
        else:
  
            print(f"心情:😢 不开心")
  
    
  
    def time_pass(self):
  
        # 时间流逝的影响
  
        self.hunger = min(100, self.hunger + 5)
  
        self.happiness = max(0, self.happiness - 3)
  
        self.age += 1
  
        
  
        # 随机事件
  
        event = random.randint(1, 10)
  
        if event == 1:
  
            print(f"💝 {self.name}找到了一个玩具,快乐度+5!")
  
            self.happiness = min(100, self.happiness + 5)
  
        elif event == 2:
  
            print(f"🌧️ 下雨了,{self.name}有点郁闷,快乐度-5")
  
            self.happiness = max(0, self.happiness - 5)
  

  
# 游戏主程序
  
def main():
  
    print("=== 虚拟宠物养成游戏 ===")
  
    
  
    pet_name = input("给你的宠物起个名字:")
  
    print("\n选择宠物类型:")
  
    print("1. 🐶 小狗")
  
    print("2. 🐱 小猫")
  
    print("3. 🐰 小兔子")
  
    
  
    choice = input("请选择(1-3):")
  
    pet_types = {
  
        "1": "小狗",
  
        "2": "小猫",
  
        "3": "小兔子"
  
    }
  
    
  
    pet_type = pet_types.get(choice, "神秘宠物")
  
    my_pet = VirtualPet(pet_name, pet_type)
  
    
  
    print(f"\n恭喜你获得了一只{pet_type}!好好照顾{pet_name}吧!")
  
    
  
    while my_pet.is_alive:
  
        my_pet.show_status()
  
        
  
        print("\n你想做什么?")
  
        print("1. 🍖 喂食")
  
        print("2. 🎮 玩耍")
  
        print("3. 😴 睡觉")
  
        print("4. ⏭️  什么都不做")
  
        print("5. 👋 退出游戏")
  
        
  
        action = input("请选择(1-5):")
  
        
  
        if action == "1":
  
            my_pet.feed()
  
        elif action == "2":
  
            my_pet.play()
  
        elif action == "3":
  
            my_pet.sleep()
  
        elif action == "4":
  
            print("时间流逝...")
  
        elif action == "5":
  
            print(f"再见!记得回来看{pet_name}哦!")
  
            break
  
        else:
  
            print("无效选择")
  
            continue
  
        
  
        # 时间流逝
  
        my_pet.time_pass()
  
        my_pet.check_status()
  
        
  
        if not my_pet.is_alive:
  
            print(f"\n游戏结束。{pet_name}活了{my_pet.age}天。")
  
            print("下次要更好地照顾你的宠物哦!")
  

  
if __name__ == "__main__":
  
    main()
  

第十三章:错误处理——让程序更强壮

13.1 什么是错误?

编程时难免会遇到错误,就像我们做数学题可能会算错一样。Python会告诉我们哪里出错了,这样我们就能修正它。

  
# 常见的错误类型
  

  
# 1. 语法错误 - 代码写错了
  
# print("Hello"  # 缺少右括号
  

  
# 2. 名称错误 - 使用了不存在的变量
  
# print(my_variable)  # my_variable没有定义
  

  
# 3. 类型错误 - 对错误的类型进行操作
  
# number = "5"
  
# result = number + 10  # 不能把字符串和数字相加
  

  
# 4. 索引错误 - 访问了不存在的位置
  
# my_list = [1, 2, 3]
  
# print(my_list[10])  # 列表只有3个元素
  

  
# 5. 零除错误
  
# result = 10 / 0  # 不能除以零
  

13.2 处理错误 - try和except

  
# 基本的错误处理
  
try:
  
    number = int(input("请输入一个数字:"))
  
    result = 10 / number
  
    print(f"10除以{number}等于{result}")
  
except ValueError:
  
    print("输入的不是有效的数字!")
  
except ZeroDivisionError:
  
    print("不能除以零!")
  

  
# 处理多种错误
  
def safe_divide():
  
    try:
  
        a = float(input("请输入被除数:"))
  
        b = float(input("请输入除数:"))
  
        result = a / b
  
        print(f"{a} ÷ {b} = {result}")
  
    except ValueError:
  
        print("❌ 请输入有效的数字!")
  
    except ZeroDivisionError:
  
        print("❌ 除数不能为零!")
  
    except Exception as e:
  
        print(f"❌ 发生了错误:{e}")
  

  
safe_divide()
  

13.3 创建一个防错的计算器

  
def safe_calculator():
  
    print("=== 安全计算器 ===")
  
    print("支持的运算:+, -, *, /")
  
    
  
    while True:
  
        try:
  
            # 获取用户输入
  
            expression = input("\n请输入算式(如:5 + 3)或输入'退出'结束:")
  
            
  
            if expression == "退出":
  
                print("再见!")
  
                break
  
            
  
            # 分解算式
  
            parts = expression.split()
  
            if len(parts) != 3:
  
                print("❌ 格式错误!请输入如 '5 + 3' 的格式")
  
                continue
  
            
  
            num1 = float(parts[0])
  
            operator = parts[1]
  
            num2 = float(parts[2])
  
            
  
            # 执行计算
  
            if operator == '+':
  
                result = num1 + num2
  
            elif operator == '-':
  
                result = num1 - num2
  
            elif operator == '*':
  
                result = num1 * num2
  
            elif operator == '/':
  
                if num2 == 0:
  
                    print("❌ 不能除以零!")
  
                    continue
  
                result = num1 / num2
  
            else:
  
                print("❌ 不支持的运算符!")
  
                continue
  
            
  
            print(f"✅ 结果:{num1} {operator} {num2} = {result}")
  
            
  
        except ValueError:
  
            print("❌ 请输入有效的数字!")
  
        except Exception as e:
  
            print(f"❌ 发生错误:{e}")
  

  
safe_calculator()
  

13.4 文件操作的错误处理

  
def safe_file_reader():
  
    filename = input("请输入要读取的文件名:")
  
    
  
    try:
  
        with open(filename, 'r', encoding='utf-8') as file:
  
            content = file.read()
  
            print(f"\n文件内容:\n{content}")
  
    except FileNotFoundError:
  
        print(f"❌ 找不到文件 '{filename}'")
  
        create = input("是否创建这个文件?(是/否): ")
  
        if create == "是":
  
            try:
  
                with open(filename, 'w', encoding='utf-8') as file:
  
                    file.write("这是一个新创建的文件!")
  
                print("✅ 文件创建成功!")
  
            except Exception as e:
  
                print(f"❌ 创建文件失败:{e}")
  
    except PermissionError:
  
        print(f"❌ 没有权限读取文件 '{filename}'")
  
    except Exception as e:
  
        print(f"❌ 读取文件时发生错误:{e}")
  

  
safe_file_reader()
  

13.5 创建一个健壮的成绩管理系统

  
class GradeManager:
  
    def __init__(self):
  
        self.students = {}
  
    
  
    def add_student(self):
  
        try:
  
            name = input("学生姓名:").strip()
  
            if not name:
  
                raise ValueError("姓名不能为空")
  
            if name in self.students:
  
                raise ValueError("该学生已存在")
  
            
  
            self.students[name] = {}
  
            print(f"✅ 学生 {name} 添加成功!")
  
        except ValueError as e:
  
            print(f"❌ 错误:{e}")
  
    
  
    def add_grade(self):
  
        try:
  
            name = input("学生姓名:").strip()
  
            if name not in self.students:
  
                raise ValueError("找不到该学生")
  
            
  
            subject = input("科目:").strip()
  
            if not subject:
  
                raise ValueError("科目不能为空")
  
            
  
            score = input("分数:").strip()
  
            score = float(score)
  
            
  
            if score < 0 or score > 100:
  
                raise ValueError("分数必须在0-100之间")
  
            
  
            self.students[name][subject] = score
  
            print(f"✅ 成绩录入成功!")
  
            
  
        except ValueError as e:
  
            if "could not convert" in str(e):
  
                print("❌ 错误:分数必须是数字")
  
            else:
  
                print(f"❌ 错误:{e}")
  
        except Exception as e:
  
            print(f"❌ 发生未知错误:{e}")
  
    
  
    def view_grades(self):
  
        try:
  
            if not self.students:
  
                print("📋 还没有学生记录")
  
                return
  
            
  
            name = input("查看哪位学生的成绩(输入'全部'查看所有):").strip()
  
            
  
            if name == '全部':
  
                for student, grades in self.students.items():
  
                    print(f"\n📊 {student}的成绩:")
  
                    if grades:
  
                        for subject, score in grades.items():
  
                            print(f"  {subject}: {score}分")
  
                        avg = sum(grades.values()) / len(grades)
  
                        print(f"  平均分: {avg:.1f}")
  
                    else:
  
                        print("  还没有成绩记录")
  
            elif name in self.students:
  
                grades = self.students[name]
  
                if grades:
  
                    print(f"\n📊 {name}的成绩:")
  
                    for subject, score in grades.items():
  
                        print(f"  {subject}: {score}分")
  
                    avg = sum(grades.values()) / len(grades)
  
                    print(f"  平均分: {avg:.1f}")
  
                else:
  
                    print(f"{name}还没有成绩记录")
  
            else:
  
                raise ValueError("找不到该学生")
  
                
  
        except ValueError as e:
  
            print(f"❌ 错误:{e}")
  
        except Exception as e:
  
            print(f"❌ 发生错误:{e}")
  
    
  
    def save_data(self):
  
        try:
  
            import json
  
            with open("grades.json", "w", encoding="utf-8") as file:
  
                json.dump(self.students, file, ensure_ascii=False, indent=2)
  
            print("✅ 数据保存成功!")
  
        except Exception as e:
  
            print(f"❌ 保存失败:{e}")
  
    
  
    def load_data(self):
  
        try:
  
            import json
  
            with open("grades.json", "r", encoding="utf-8") as file:
  
                self.students = json.load(file)
  
            print("✅ 数据加载成功!")
  
        except FileNotFoundError:
  
            print("📋 没有找到保存的数据,将创建新的记录")
  
        except Exception as e:
  
            print(f"❌ 加载数据失败:{e}")
  
    
  
    def run(self):
  
        print("=== 成绩管理系统 v2.0 ===")
  
        self.load_data()
  
        
  
        while True:
  
            print("\n1. 添加学生")
  
            print("2. 录入成绩")
  
            print("3. 查看成绩")
  
            print("4. 保存数据")
  
            print("5. 退出")
  
            
  
            try:
  
                choice = input("请选择(1-5):").strip()
  
                
  
                if choice == "1":
  
                    self.add_student()
  
                elif choice == "2":
  
                    self.add_grade()
  
                elif choice == "3":
  
                    self.view_grades()
  
                elif choice == "4":
  
                    self.save_data()
  
                elif choice == "5":
  
                    save = input("退出前是否保存?(是/否): ")
  
                    if save == "是":
  
                        self.save_data()
  
                    print("再见!")
  
                    break
  
                else:
  
                    print("❌ 无效的选择,请输入1-5")
  
                    
  
            except KeyboardInterrupt:
  
                print("\n\n程序被中断")
  
                break
  
            except Exception as e:
  
                print(f"❌ 发生错误:{e}")
  

  
# 运行程序
  
if __name__ == "__main__":
  
    manager = GradeManager()
  
    manager.run()
  

第十四章:小项目实战——综合运用所学知识

14.1 项目一:天气记录器

  
import datetime
  
import json
  
import os
  

  
class WeatherDiary:
  
    def __init__(self):
  
        self.filename = "weather_diary.json"
  
        self.records = self.load_records()
  
    
  
    def load_records(self):
  
        """加载已有的天气记录"""
  
        if os.path.exists(self.filename):
  
            try:
  
                with open(self.filename, 'r', encoding='utf-8') as file:
  
                    return json.load(file)
  
            except:
  
                return {}
  
        return {}
  
    
  
    def save_records(self):
  
        """保存天气记录"""
  
        with open(self.filename, 'w', encoding='utf-8') as file:
  
            json.dump(self.records, file, ensure_ascii=False, indent=2)
  
    
  
    def add_record(self):
  
        """添加今天的天气记录"""
  
        today = datetime.date.today().strftime("%Y-%m-%d")
  
        
  
        print(f"\n📅 记录日期:{today}")
  
        
  
        # 天气选项
  
        weather_options = ["☀️ 晴天", "☁️ 多云", "🌧️ 雨天", "❄️ 雪天", "🌫️ 雾天"]
  
        print("\n选择今天的天气:")
  
        for i, weather in enumerate(weather_options, 1):
  
            print(f"{i}. {weather}")
  
        
  
        try:
  
            choice = int(input("请选择(1-5):"))
  
            weather = weather_options[choice - 1]
  
        except:
  
            print("❌ 无效选择,默认设为晴天")
  
            weather = weather_options[0]
  
        
  
        # 温度
  
        try:
  
            temp = float(input("今天的温度(℃):"))
  
        except:
  
            temp = 20.0
  
            print("❌ 无效输入,默认设为20℃")
  
        
  
        # 心情
  
        mood = input("今天的心情如何?")
  
        
  
        # 保存记录
  
        self.records[today] = {
  
            "weather": weather,
  
            "temperature": temp,
  
            "mood": mood,
  
            "timestamp": datetime.datetime.now().strftime("%H:%M:%S")
  
        }
  
        
  
        self.save_records()
  
        print("✅ 天气记录已保存!")
  
    
  
    def view_records(self):
  
        """查看天气记录"""
  
        if not self.records:
  
            print("📋 还没有天气记录")
  
            return
  
        
  
        print("\n=== 天气记录 ===")
  
        # 按日期排序
  
        sorted_dates = sorted(self.records.keys(), reverse=True)
  
        
  
        for date in sorted_dates[:7]:  # 显示最近7天
  
            record = self.records[date]
  
            print(f"\n📅 {date}")
  
            print(f"  天气:{record['weather']}")
  
            print(f"  温度:{record['temperature']}℃")
  
            print(f"  心情:{record['mood']}")
  
    
  
    def weather_statistics(self):
  
        """天气统计"""
  
        if not self.records:
  
            print("📋 还没有足够的数据进行统计")
  
            return
  
        
  
        # 统计各种天气出现的次数
  
        weather_count = {}
  
        total_temp = 0
  
        
  
        for record in self.records.values():
  
            weather = record['weather']
  
            weather_count[weather] = weather_count.get(weather, 0) + 1
  
            total_temp += record['temperature']
  
        
  
        print("\n=== 天气统计 ===")
  
        print(f"总记录天数:{len(self.records)}")
  
        print(f"平均温度:{total_temp / len(self.records):.1f}℃")
  
        
  
        print("\n各种天气出现次数:")
  
        for weather, count in weather_count.items():
  
            percentage = count / len(self.records) * 100
  
            print(f"{weather}: {count}次 ({percentage:.1f}%)")
  
    
  
    def run(self):
  
        """主程序"""
  
        print("=== 天气记录器 ===")
  
        
  
        while True:
  
            print("\n1. 📝 记录今天的天气")
  
            print("2. 📊 查看天气记录")
  
            print("3. 📈 天气统计")
  
            print("4. 🚪 退出")
  
            
  
            choice = input("请选择(1-4):")
  
            
  
            if choice == "1":
  
                self.add_record()
  
            elif choice == "2":
  
                self.view_records()
  
            elif choice == "3":
  
                self.weather_statistics()
  
            elif choice == "4":
  
                print("再见!记得每天记录天气哦!")
  
                break
  
            else:
  
                print("❌ 无效选择")
  

  
# 运行天气记录器
  
if __name__ == "__main__":
  
    diary = WeatherDiary()
  
    diary.run()
  

14.2 项目二:单词记忆游戏

  
import random
  
import time
  
import json
  

  
class WordMemoryGame:
  
    def __init__(self):
  
        self.words = {
  
            "easy": {
  
                "cat": "猫",
  
                "dog": "狗",
  
                "book": "书",
  
                "pen": "笔",
  
                "red": "红色",
  
                "blue": "蓝色",
  
                "happy": "快乐",
  
                "sad": "悲伤",
  
                "big": "大",
  
                "small": "小"
  
            },
  
            "medium": {
  
                "computer": "电脑",
  
                "elephant": "大象",
  
                "beautiful": "美丽的",
  
                "important": "重要的",
  
                "breakfast": "早餐",
  
                "homework": "作业",
  
                "friend": "朋友",
  
                "family": "家庭",
  
                "teacher": "老师",
  
                "student": "学生"
  
            },
  
            "hard": {
  
                "dictionary": "字典",
  
                "environment": "环境",
  
                "technology": "技术",
  
                "international": "国际的",
  
                "communication": "交流",
  
                "congratulations": "祝贺",
  
                "responsibility": "责任",
  
                "achievement": "成就",
  
                "knowledge": "知识",
  
                "experience": "经验"
  
            }
  
        }
  
        self.score = 0
  
        self.high_scores = self.load_high_scores()
  
    
  
    def load_high_scores(self):
  
        """加载最高分记录"""
  
        try:
  
            with open("word_game_scores.json", "r") as file:
  
                return json.load(file)
  
        except:
  
            return {"easy": 0, "medium": 0, "hard": 0}
  
    
  
    def save_high_scores(self):
  
        """保存最高分"""
  
        with open("word_game_scores.json", "w") as file:
  
            json.dump(self.high_scores, file)
  
    
  
    def play_round(self, difficulty):
  
        """进行一轮游戏"""
  
        word_dict = self.words[difficulty]
  
        words_list = list(word_dict.items())
  
        random.shuffle(words_list)
  
        
  
        correct = 0
  
        total = min(5, len(words_list))  # 每轮5个单词
  
        
  
        print(f"\n=== {difficulty.upper()} 难度 ===")
  
        print(f"准备好了吗?游戏即将开始!\n")
  
        time.sleep(2)
  
        
  
        for i in range(total):
  
            english, chinese = words_list[i]
  
            
  
            print(f"\n第 {i+1}/{total} 题")
  
            print(f"请问 '{english}' 的中文意思是什么?")
  
            
  
            # 生成选项
  
            options = [chinese]
  
            other_meanings = [meaning for _, meaning in word_dict.items() if meaning != chinese]
  
            options.extend(random.sample(other_meanings, min(3, len(other_meanings))))
  
            random.shuffle(options)
  
            
  
            # 显示选项
  
            for j, option in enumerate(options, 1):
  
                print(f"{j}. {option}")
  
            
  
            # 获取答案
  
            try:
  
                answer = int(input("你的选择(输入数字):"))
  
                if 1 <= answer <= len(options) and options[answer-1] == chinese:
  
                    print("✅ 正确!")
  
                    correct += 1
  
                    self.score += {"easy": 10, "medium": 20, "hard": 30}[difficulty]
  
                else:
  
                    print(f"❌ 错误!正确答案是:{chinese}")
  
            except:
  
                print(f"❌ 错误!正确答案是:{chinese}")
  
        
  
        # 显示本轮成绩
  
        accuracy = correct / total * 100
  
        print(f"\n本轮成绩:{correct}/{total} (正确率:{accuracy:.0f}%)")
  
        print(f"当前总分:{self.score}")
  
        
  
        # 更新最高分
  
        if self.score > self.high_scores[difficulty]:
  
            self.high_scores[difficulty] = self.score
  
            print(f"🎉 新纪录!{difficulty}难度最高分:{self.score}")
  
            self.save_high_scores()
  
    
  
    def study_mode(self):
  
        """学习模式 - 浏览所有单词"""
  
        print("\n=== 学习模式 ===")
  
        print("选择要学习的难度:")
  
        print("1. Easy (简单)")
  
        print("2. Medium (中等)")
  
        print("3. Hard (困难)")
  
        
  
        choice = input("请选择(1-3):")
  
        difficulty_map = {"1": "easy", "2": "medium", "3": "hard"}
  
        
  
        if choice not in difficulty_map:
  
            print("❌ 无效选择")
  
            return
  
        
  
        difficulty = difficulty_map[choice]
  
        word_dict = self.words[difficulty]
  
        
  
        print(f"\n{difficulty.upper()} 难度的单词:")
  
        for english, chinese in word_dict.items():
  
            print(f"{english:20} - {chinese}")
  
            time.sleep(0.5)  # 慢慢显示,方便记忆
  
    
  
    def show_high_scores(self):
  
        """显示最高分"""
  
        print("\n=== 最高分记录 ===")
  
        for difficulty, score in self.high_scores.items():
  
            print(f"{difficulty.capitalize():10} : {score} 分")
  
    
  
    def run(self):
  
        """主程序"""
  
        print("=== 单词记忆游戏 ===")
  
        print("通过游戏学习英语单词!")
  
        
  
        while True:
  
            print("\n1. 🎮 开始游戏")
  
            print("2. 📚 学习模式")
  
            print("3. 🏆 查看最高分")
  
            print("4. 🚪 退出游戏")
  
            
  
            choice = input("请选择(1-4):")
  
            
  
            if choice == "1":
  
                print("\n选择难度:")
  
                print("1. Easy (简单)")
  
                print("2. Medium (中等)")
  
                print("3. Hard (困难)")
  
                
  
                diff_choice = input("请选择(1-3):")
  
                difficulty_map = {"1": "easy", "2": "medium", "3": "hard"}
  
                
  
                if diff_choice in difficulty_map:
  
                    self.score = 0  # 重置分数
  
                    self.play_round(difficulty_map[diff_choice])
  
                else:
  
                    print("❌ 无效选择")
  
            
  
            elif choice == "2":
  
                self.study_mode()
  
            
  
            elif choice == "3":
  
                self.show_high_scores()
  
            
  
            elif choice == "4":
  
                print("再见!继续努力学习英语哦!")
  
                break
  
            
  
            else:
  
                print("❌ 无效选择")
  

  
# 运行游戏
  
if __name__ == "__main__":
  
    game = WordMemoryGame()
  
    game.run()
  

14.3 项目三:班级值日表管理系统

  
import datetime
  
import json
  
import random
  

  
class DutyScheduler:
  
    def __init__(self):
  
        self.students = []
  
        self.schedule = {}
  
        self.tasks = ["擦黑板", "扫地", "拖地", "倒垃圾", "整理讲台", "浇花"]
  
        self.load_data()
  
    
  
    def load_data(self):
  
        """加载数据"""
  
        try:
  
            with open("duty_data.json", "r", encoding="utf-8") as file:
  
                data = json.load(file)
  
                self.students = data.get("students", [])
  
                self.schedule = data.get("schedule", {})
  
        except:
  
            pass
  
    
  
    def save_data(self):
  
        """保存数据"""
  
        data = {
  
            "students": self.students,
  
            "schedule": self.schedule
  
        }
  
        with open("duty_data.json", "w", encoding="utf-8") as file:
  
            json.dump(data, file, ensure_ascii=False, indent=2)
  
    
  
    def manage_students(self):
  
        """管理学生名单"""
  
        while True:
  
            print(f"\n当前学生名单({len(self.students)}人):")
  
            if self.students:
  
                for i, student in enumerate(self.students, 1):
  
                    print(f"{i}. {student}")
  
            else:
  
                print("还没有学生")
  
            
  
            print("\n1. 添加学生")
  
            print("2. 删除学生")
  
            print("3. 返回主菜单")
  
            
  
            choice = input("请选择(1-3):")
  
            
  
            if choice == "1":
  
                name = input("学生姓名:").strip()
  
                if name and name not in self.students:
  
                    self.students.append(name)
  
                    print(f"✅ {name} 已添加")
  
                    self.save_data()
  
                else:
  
                    print("❌ 姓名无效或已存在")
  
            
  
            elif choice == "2":
  
                if self.students:
  
                    try:
  
                        index = int(input("要删除的学生编号:")) - 1
  
                        if 0 <= index < len(self.students):
  
                            removed = self.students.pop(index)
  
                            print(f"✅ {removed} 已删除")
  
                            self.save_data()
  
                        else:
  
                            print("❌ 无效的编号")
  
                    except:
  
                        print("❌ 请输入有效的数字")
  
                else:
  
                    print("❌ 没有可删除的学生")
  
            
  
            elif choice == "3":
  
                break
  
    
  
    def generate_schedule(self):
  
        """生成值日表"""
  
        if len(self.students) < len(self.tasks):
  
            print(f"❌ 学生人数({len(self.students)})少于任务数({len(self.tasks)})")
  
            print("请先添加更多学生")
  
            return
  
        
  
        # 获取日期范围
  
        try:
  
            days = int(input("生成几天的值日表?"))
  
            if days <= 0:
  
                raise ValueError
  
        except:
  
            print("❌ 请输入有效的天数")
  
            return
  
        
  
        # 生成值日表
  
        start_date = datetime.date.today()
  
        
  
        for i in range(days):
  
            current_date = start_date + datetime.timedelta(days=i)
  
            date_str = current_date.strftime("%Y-%m-%d")
  
            
  
            # 为这一天随机分配学生
  
            available_students = self.students.copy()
  
            random.shuffle(available_students)
  
            
  
            day_schedule = {}
  
            for j, task in enumerate(self.tasks):
  
                if j < len(available_students):
  
                    day_schedule[task] = available_students[j]
  
            
  
            self.schedule[date_str] = day_schedule
  
        
  
        self.save_data()
  
        print(f"✅ 已生成{days}天的值日表")
  
    
  
    def view_schedule(self):
  
        """查看值日表"""
  
        if not self.schedule:
  
            print("📋 还没有值日表")
  
            return
  
        
  
        print("\n查看选项:")
  
        print("1. 今天的值日安排")
  
        print("2. 本周的值日安排")
  
        print("3. 查看特定日期")
  
        print("4. 查看所有安排")
  
        
  
        choice = input("请选择(1-4):")
  
        
  
        if choice == "1":
  
            today = datetime.date.today().strftime("%Y-%m-%d")
  
            if today in self.schedule:
  
                self._print_day_schedule(today)
  
            else:
  
                print("❌ 今天没有值日安排")
  
        
  
        elif choice == "2":
  
            today = datetime.date.today()
  
            monday = today - datetime.timedelta(days=today.weekday())
  
            
  
            print("\n=== 本周值日表 ===")
  
            for i in range(7):
  
                date = monday + datetime.timedelta(days=i)
  
                date_str = date.strftime("%Y-%m-%d")
  
                if date_str in self.schedule:
  
                    self._print_day_schedule(date_str)
  
        
  
        elif choice == "3":
  
            date_str = input("请输入日期(格式:YYYY-MM-DD):")
  
            if date_str in self.schedule:
  
                self._print_day_schedule(date_str)
  
            else:
  
                print("❌ 该日期没有值日安排")
  
        
  
        elif choice == "4":
  
            sorted_dates = sorted(self.schedule.keys())
  
            for date_str in sorted_dates:
  
                self._print_day_schedule(date_str)
  
    
  
    def _print_day_schedule(self, date_str):
  
        """打印某一天的值日安排"""
  
        # 解析日期
  
        date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
  
        weekday = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"][date.weekday()]
  
        
  
        print(f"\n📅 {date_str} {weekday}")
  
        day_schedule = self.schedule[date_str]
  
        for task, student in day_schedule.items():
  
            print(f"  {task}: {student}")
  
    
  
    def check_duty_record(self):
  
        """查看值日统计"""
  
        if not self.schedule:
  
            print("📋 还没有值日记录")
  
            return
  
        
  
        # 统计每个学生的值日次数
  
        duty_count = {}
  
        for day_schedule in self.schedule.values():
  
            for task, student in day_schedule.items():
  
                if student not in duty_count:
  
                    duty_count[student] = {"total": 0, "tasks": {}}
  
                duty_count[student]["total"] += 1
  
                duty_count[student]["tasks"][task] = duty_count[student]["tasks"].get(task, 0) + 1
  
        
  
        print("\n=== 值日统计 ===")
  
        for student in sorted(duty_count.keys()):
  
            info = duty_count[student]
  
            print(f"\n{student}:")
  
            print(f"  总值日次数:{info['total']}")
  
            print("  各项任务次数:")
  
            for task, count in info["tasks"].items():
  
                print(f"    {task}: {count}次")
  
    
  
    def run(self):
  
        """主程序"""
  
        print("=== 班级值日表管理系统 ===")
  
        
  
        while True:
  
            print("\n1. 👥 管理学生名单")
  
            print("2. 📝 生成值日表")
  
            print("3. 📅 查看值日表")
  
            print("4. 📊 值日统计")
  
            print("5. 🚪 退出系统")
  
            
  
            choice = input("请选择(1-5):")
  
            
  
            if choice == "1":
  
                self.manage_students()
  
            elif choice == "2":
  
                self.generate_schedule()
  
            elif choice == "3":
  
                self.view_schedule()
  
            elif choice == "4":
  
                self.check_duty_record()
  
            elif choice == "5":
  
                print("再见!")
  
                break
  
            else:
  
                print("❌ 无效选择")
  

  
# 运行系统
  
if __name__ == "__main__":
  
    scheduler = DutyScheduler()
  
    scheduler.run()
  

第十五章:Python进阶探索

15.1 模块和包

当我们的程序越来越大时,把所有代码放在一个文件里会变得很难管理。这时我们可以把代码分成不同的模块(文件)。

  
# math_tools.py - 数学工具模块
  
def add(a, b):
  
    """加法"""
  
    return a + b
  

  
def multiply(a, b):
  
    """乘法"""
  
    return a * b
  

  
def factorial(n):
  
    """计算阶乘"""
  
    if n <= 1:
  
        return 1
  
    return n * factorial(n - 1)
  

  
def is_prime(n):
  
    """判断是否为质数"""
  
    if n < 2:
  
        return False
  
    for i in range(2, int(n ** 0.5) + 1):
  
        if n % i == 0:
  
            return False
  
    return True
  

  
# main.py - 主程序
  
import math_tools
  

  
# 使用模块中的函数
  
print(math_tools.add(5, 3))
  
print(math_tools.factorial(5))
  
print(math_tools.is_prime(17))
  

15.2 使用标准库

Python自带了很多有用的模块,我们可以直接使用:

  
# 1. random - 随机数模块
  
import random
  

  
# 随机整数
  
dice = random.randint(1, 6)
  
print(f"掷骰子:{dice}")
  

  
# 随机选择
  
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
  
choice = random.choice(fruits)
  
print(f"随机水果:{choice}")
  

  
# 打乱列表
  
cards = list(range(1, 11))
  
random.shuffle(cards)
  
print(f"洗牌后:{cards}")
  

  
# 2. datetime - 日期时间模块
  
import datetime
  

  
# 当前时间
  
now = datetime.datetime.now()
  
print(f"现在是:{now.strftime('%Y年%m月%d日 %H:%M:%S')}")
  

  
# 计算年龄
  
birthday = datetime.date(2014, 5, 20)
  
today = datetime.date.today()
  
age = today.year - birthday.year
  
print(f"年龄:{age}岁")
  

  
# 3. os - 操作系统模块
  
import os
  

  
# 获取当前目录
  
current_dir = os.getcwd()
  
print(f"当前目录:{current_dir}")
  

  
# 列出目录内容
  
files = os.listdir(".")
  
print(f"目录内容:{files}")
  

  
# 4. math - 数学模块
  
import math
  

  
# 数学常数
  
print(f"圆周率:{math.pi}")
  
print(f"自然常数:{math.e}")
  

  
# 数学函数
  
print(f"16的平方根:{math.sqrt(16)}")
  
print(f"2的8次方:{math.pow(2, 8)}")
  
print(f"sin(90°):{math.sin(math.radians(90))}")
  

15.3 简单的网络编程

  
# 获取网页内容(需要安装requests: pip install requests)
  
import requests
  

  
def get_joke():
  
    """从API获取一个笑话"""
  
    try:
  
        # 这是一个返回随机笑话的API
  
        response = requests.get("https://official-joke-api.appspot.com/random_joke")
  
        if response.status_code == 200:
  
            joke_data = response.json()
  
            print(f"Q: {joke_data['setup']}")
  
            input("按回车看答案...")
  
            print(f"A: {joke_data['punchline']}")
  
        else:
  
            print("获取笑话失败")
  
    except Exception as e:
  
        print(f"出错了:{e}")
  

  
# 简单的天气查询(示例)
  
def check_weather_example():
  
    """模拟天气查询"""
  
    cities = {
  
        "北京": {"temp": 25, "weather": "晴"},
  
        "上海": {"temp": 28, "weather": "多云"},
  
        "广州": {"temp": 32, "weather": "雨"},
  
        "成都": {"temp": 22, "weather": "阴"}
  
    }
  
    
  
    city = input("查询哪个城市的天气?")
  
    if city in cities:
  
        info = cities[city]
  
        print(f"{city}天气:{info['weather']},温度:{info['temp']}℃")
  
    else:
  
        print("暂不支持该城市")
  

15.4 简单的数据分析

  
# 学生成绩分析系统
  
class GradeAnalyzer:
  
    def __init__(self):
  
        self.students_data = {}
  
    
  
    def add_student_grades(self, name, grades):
  
        """添加学生成绩"""
  
        self.students_data[name] = grades
  
    
  
    def analyze_student(self, name):
  
        """分析单个学生"""
  
        if name not in self.students_data:
  
            print(f"找不到学生:{name}")
  
            return
  
        
  
        grades = self.students_data[name]
  
        total = sum(grades.values())
  
        average = total / len(grades)
  
        highest = max(grades.values())
  
        lowest = min(grades.values())
  
        
  
        print(f"\n{name}的成绩分析:")
  
        print(f"总分:{total}")
  
        print(f"平均分:{average:.1f}")
  
        print(f"最高分:{highest} ({[k for k, v in grades.items() if v == highest][0]})")
  
        print(f"最低分:{lowest} ({[k for k, v in grades.items() if v == lowest][0]})")
  
        
  
        # 成绩评级
  
        if average >= 90:
  
            grade = "A (优秀)"
  
        elif average >= 80:
  
            grade = "B (良好)"
  
        elif average >= 70:
  
            grade = "C (中等)"
  
        elif average >= 60:
  
            grade = "D (及格)"
  
        else:
  
            grade = "F (需要努力)"
  
        
  
        print(f"综合评级:{grade}")
  
    
  
    def class_statistics(self):
  
        """班级统计"""
  
        if not self.students_data:
  
            print("还没有数据")
  
            return
  
        
  
        # 计算各科平均分
  
        subjects = set()
  
        for grades in self.students_data.values():
  
            subjects.update(grades.keys())
  
        
  
        print("\n班级统计报告:")
  
        print(f"学生人数:{len(self.students_data)}")
  
        
  
        print("\n各科平均分:")
  
        for subject in subjects:
  
            scores = [grades.get(subject, 0) for grades in self.students_data.values()]
  
            avg = sum(scores) / len(scores)
  
            print(f"{subject}: {avg:.1f}分")
  
        
  
        # 找出班级前三名
  
        student_averages = {}
  
        for name, grades in self.students_data.items():
  
            avg = sum(grades.values()) / len(grades)
  
            student_averages[name] = avg
  
        
  
        top_students = sorted(student_averages.items(), key=lambda x: x[1], reverse=True)[:3]
  
        
  
        print("\n班级前三名:")
  
        for i, (name, avg) in enumerate(top_students, 1):
  
            print(f"{i}. {name} - 平均分:{avg:.1f}")
  
    
  
    def generate_report(self):
  
        """生成成绩报告"""
  
        with open("class_report.txt", "w", encoding="utf-8") as file:
  
            file.write("=== 班级成绩报告 ===\n")
  
            file.write(f"生成时间:{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
  
            
  
            for name, grades in self.students_data.items():
  
                file.write(f"{name}的成绩:\n")
  
                for subject, score in grades.items():
  
                    file.write(f"  {subject}: {score}分\n")
  
                avg = sum(grades.values()) / len(grades)
  
                file.write(f"  平均分: {avg:.1f}\n\n")
  
        
  
        print("✅ 报告已生成:class_report.txt")
  

  
# 使用示例
  
analyzer = GradeAnalyzer()
  
analyzer.add_student_grades("小明", {"语文": 85, "数学": 92, "英语": 88})
  
analyzer.add_student_grades("小红", {"语文": 92, "数学": 88, "英语": 95})
  
analyzer.add_student_grades("小华", {"语文": 78, "数学": 85, "英语": 82})
  

  
analyzer.analyze_student("小明")
  
analyzer.class_statistics()
  
analyzer.generate_report()
  

15.5 创建你的第一个GUI程序

  
import tkinter as tk
  
from tkinter import messagebox
  
import random
  

  
class NumberGuessingGUI:
  
    def __init__(self):
  
        self.window = tk.Tk()
  
        self.window.title("猜数字游戏")
  
        self.window.geometry("400x300")
  
        
  
        self.secret_number = random.randint(1, 100)
  
        self.attempts = 0
  
        
  
        self.create_widgets()
  
    
  
    def create_widgets(self):
  
        # 标题
  
        title_label = tk.Label(
  
            self.window, 
  
            text="猜数字游戏", 
  
            font=("Arial", 20, "bold")
  
        )
  
        title_label.pack(pady=20)
  
        
  
        # 说明
  
        info_label = tk.Label(
  
            self.window,
  
            text="我想了一个1到100之间的数字,你能猜到吗?",
  
            font=("Arial", 12)
  
        )
  
        info_label.pack()
  
        
  
        # 输入框
  
        self.entry = tk.Entry(self.window, font=("Arial", 14), width=10)
  
        self.entry.pack(pady=20)
  
        self.entry.bind("<Return>", lambda e: self.check_guess())
  
        
  
        # 猜测按钮
  
        guess_button = tk.Button(
  
            self.window,
  
            text="猜!",
  
            command=self.check_guess,
  
            font=("Arial", 14),
  
            bg="lightblue",
  
            width=10
  
        )
  
        guess_button.pack()
  
        
  
        # 反馈标签
  
        self.feedback_label = tk.Label(
  
            self.window,
  
            text="",
  
            font=("Arial", 12),
  
            fg="blue"
  
        )
  
        self.feedback_label.pack(pady=20)
  
        
  
        # 重新开始按钮
  
        restart_button = tk.Button(
  
            self.window,
  
            text="重新开始",
  
            command=self.restart_game,
  
            font=("Arial", 12)
  
        )
  
        restart_button.pack()
  
    
  
    def check_guess(self):
  
        try:
  
            guess = int(self.entry.get())
  
            self.attempts += 1
  
            
  
            if guess == self.secret_number:
  
                messagebox.showinfo(
  
                    "恭喜!",
  
                    f"你猜对了!\n数字是{self.secret_number}\n你用了{self.attempts}次"
  
                )
  
                self.restart_game()
  
            elif guess < self.secret_number:
  
                self.feedback_label.config(text="太小了!再大一点", fg="red")
  
            else:
  
                self.feedback_label.config(text="太大了!再小一点", fg="red")
  
            
  
            self.entry.delete(0, tk.END)
  
            
  
        except ValueError:
  
            messagebox.showerror("错误", "请输入一个有效的数字!")
  
    
  
    def restart_game(self):
  
        self.secret_number = random.randint(1, 100)
  
        self.attempts = 0
  
        self.entry.delete(0, tk.END)
  
        self.feedback_label.config(text="")
  
    
  
    def run(self):
  
        self.window.mainloop()
  

  
# 简单的计算器GUI
  
class SimpleCalculatorGUI:
  
    def __init__(self):
  
        self.window = tk.Tk()
  
        self.window.title("简单计算器")
  
        self.window.geometry("300x400")
  
        
  
        self.result_var = tk.StringVar()
  
        self.result_var.set("0")
  
        
  
        self.create_widgets()
  
    
  
    def create_widgets(self):
  
        # 显示屏
  
        display = tk.Label(
  
            self.window,
  
            textvariable=self.result_var,
  
            font=("Arial", 24),
  
            bg="white",
  
            anchor="e",
  
            padx=10
  
        )
  
        display.grid(row=0, column=0, columnspan=4, sticky="ew", padx=10, pady=10)
  
        
  
        # 按钮
  
        buttons = [
  
            ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
  
            ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
  
            ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
  
            ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
  
            ('C', 5, 0)
  
        ]
  
        
  
        for (text, row, col) in buttons:
  
            button = tk.Button(
  
                self.window,
  
                text=text,
  
                font=("Arial", 18),
  
                width=5,
  
                height=2,
  
                command=lambda t=text: self.button_click(t)
  
            )
  
            button.grid(row=row, column=col, padx=5, pady=5)
  
            
  
            if text == 'C':
  
                button.config(columnspan=4, width=23)
  
    
  
    def button_click(self, char):
  
        current = self.result_var.get()
  
        
  
        if char == 'C':
  
            self.result_var.set('0')
  
        elif char == '=':
  
            try:
  
                result = eval(current)
  
                self.result_var.set(str(result))
  
            except:
  
                self.result_var.set('错误')
  
        else:
  
            if current == '0' or current == '错误':
  
                self.result_var.set(char)
  
            else:
  
                self.result_var.set(current + char)
  
    
  
    def run(self):
  
        self.window.mainloop()
  

  
# 选择要运行的程序
  
print("选择要运行的GUI程序:")
  
print("1. 猜数字游戏")
  
print("2. 简单计算器")
  

  
choice = input("请选择(1-2):")
  

  
if choice == "1":
  
    game = NumberGuessingGUI()
  
    game.run()
  
elif choice == "2":
  
    calc = SimpleCalculatorGUI()
  
    calc.run()
  

结语:继续你的编程之旅

亲爱的小程序员,恭喜你完成了Python编程的基础学习!在这段旅程中,你学会了:

  1. 基础知识:变量、数据类型、输入输出

  2. 控制结构:条件判断、循环

  3. 数据结构:列表、字典

  4. 函数和类:代码重用和面向对象编程

  5. 文件操作:保存和读取数据

  6. 图形编程:用Turtle画图

  7. 错误处理:让程序更健壮

  8. 实际项目:综合运用所学知识

下一步学什么?

  1. 深入Python:学习更多高级特性,如装饰器、生成器等

  2. Web开发:用Flask或Django创建网站

  3. 数据科学:用NumPy、Pandas分析数据

  4. 人工智能:了解机器学习基础

  5. 游戏开发:用Pygame制作更复杂的游戏

编程建议

  1. 多动手实践:编程是一门实践的艺术

  2. 不怕出错:错误是最好的老师

  3. 保持好奇心:探索新的可能性

  4. 分享你的作品:和朋友一起学习

  5. 坚持不懈:每天进步一点点

记住,每一位伟大的程序员都是从"Hello, World!"开始的。保持热情,继续探索,相信有一天你会创造出令人惊叹的程序!

祝你在编程的道路上越走越远!加油!🚀