🎯 24. 实战小项目

本章概述

5个经典小项目,边学边练,巩固所学知识。 预计学习时间:每个项目 30-60 分钟


项目1:猜数字游戏

项目描述

程序随机生成一个 1-100 的数字,玩家猜数字,程序提示大了还是小了,直到猜对为止。

知识点

  • 随机数
  • 循环
  • 条件判断
  • 输入输出

参考代码

import random
 
def guess_number():
    # 生成随机数
    target = random.randint(1, 100)
    count = 0
 
    print("=== 猜数字游戏 ===")
    print("我想了一个1-100之间的数字,你来猜猜看吧!")
 
    while True:
        try:
            guess = int(input("请输入你猜的数字:"))
            count += 1
 
            if guess < target:
                print("太小了,再大一点!")
            elif guess > target:
                print("太大了,再小一点!")
            else:
                print(f"恭喜你,猜对了!答案就是{target}")
                print(f"你一共猜了{count}次")
                break
        except ValueError:
            print("请输入有效的数字!")
 
if __name__ == "__main__":
    guess_number()

扩展练习

  • 限制猜的次数(比如最多猜7次)
  • 难度选择(简单:1-50,普通:1-100,困难:1-200)
  • 记录历史成绩
  • 多人对战模式

项目2:简易计算器

项目描述

实现一个支持加减乘除的计算器。

知识点

  • 函数
  • 条件判断
  • 异常处理
  • 用户输入

参考代码

def add(a, b):
    """加法"""
    return a + b
 
def subtract(a, b):
    """减法"""
    return a - b
 
def multiply(a, b):
    """乘法"""
    return a * b
 
def divide(a, b):
    """除法"""
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b
 
def calculator():
    print("=== 简易计算器 ===")
    print("1. 加法")
    print("2. 减法")
    print("3. 乘法")
    print("4. 除法")
    print("0. 退出")
 
    while True:
        choice = input("\n请选择操作(0-4):")
 
        if choice == "0":
            print("再见!")
            break
 
        if choice not in ["1", "2", "3", "4"]:
            print("无效的选择,请重新输入")
            continue
 
        try:
            num1 = float(input("请输入第一个数:"))
            num2 = float(input("请输入第二个数:"))
 
            if choice == "1":
                result = add(num1, num2)
                print(f"{num1} + {num2} = {result}")
            elif choice == "2":
                result = subtract(num1, num2)
                print(f"{num1} - {num2} = {result}")
            elif choice == "3":
                result = multiply(num1, num2)
                print(f"{num1} × {num2} = {result}")
            elif choice == "4":
                result = divide(num1, num2)
                print(f"{num1} ÷ {num2} = {result}")
 
        except ValueError as e:
            print(f"错误:{e}")
        except Exception as e:
            print(f"发生错误:{e}")
 
if __name__ == "__main__":
    calculator()

扩展练习

  • 支持更多运算(平方、开方、取模等)
  • 支持连续计算(用上一次的结果继续运算)
  • 历史记录功能
  • 支持括号的复杂表达式计算

项目3:待办事项管理

项目描述

实现一个命令行的待办事项管理工具,可以添加、查看、完成、删除任务。

知识点

  • 列表
  • 字典
  • 函数
  • 文件操作
  • 循环

参考代码

import json
import os
 
TODO_FILE = "todos.json"
 
def load_todos():
    """从文件加载待办事项"""
    if not os.path.exists(TODO_FILE):
        return []
    with open(TODO_FILE, "r", encoding="utf-8") as f:
        return json.load(f)
 
def save_todos(todos):
    """保存待办事项到文件"""
    with open(TODO_FILE, "w", encoding="utf-8") as f:
        json.dump(todos, f, ensure_ascii=False, indent=2)
 
def add_todo(todos, title):
    """添加待办事项"""
    todo = {
        "id": len(todos) + 1,
        "title": title,
        "completed": False
    }
    todos.append(todo)
    save_todos(todos)
    print(f"已添加:{title}")
 
def show_todos(todos):
    """显示所有待办事项"""
    if not todos:
        print("暂无待办事项")
        return
 
    print("\n=== 待办事项列表 ===")
    for todo in todos:
        status = "✓" if todo["completed"] else " "
        print(f"{todo['id']}. [{status}] {todo['title']}")
 
    completed = sum(1 for t in todos if t["completed"])
    print(f"\n{len(todos)}项,已完成{completed}项")
 
def complete_todo(todos, todo_id):
    """标记完成"""
    for todo in todos:
        if todo["id"] == todo_id:
            todo["completed"] = True
            save_todos(todos)
            print(f"已完成:{todo['title']}")
            return
    print(f"找不到ID为{todo_id}的任务")
 
def delete_todo(todos, todo_id):
    """删除待办事项"""
    for i, todo in enumerate(todos):
        if todo["id"] == todo_id:
            deleted = todos.pop(i)
            save_todos(todos)
            print(f"已删除:{deleted['title']}")
            return
    print(f"找不到ID为{todo_id}的任务")
 
def main():
    todos = load_todos()
 
    print("=== 待办事项管理 ===")
    print("1. 添加任务")
    print("2. 查看所有任务")
    print("3. 标记完成")
    print("4. 删除任务")
    print("0. 退出")
 
    while True:
        choice = input("\n请选择操作(0-4):")
 
        if choice == "0":
            print("再见!")
            break
        elif choice == "1":
            title = input("请输入任务内容:")
            add_todo(todos, title)
        elif choice == "2":
            show_todos(todos)
        elif choice == "3":
            try:
                todo_id = int(input("请输入要完成的任务ID:"))
                complete_todo(todos, todo_id)
            except ValueError:
                print("请输入有效的数字")
        elif choice == "4":
            try:
                todo_id = int(input("请输入要删除的任务ID:"))
                delete_todo(todos, todo_id)
            except ValueError:
                print("请输入有效的数字")
        else:
            print("无效的选择")
 
if __name__ == "__main__":
    main()

扩展练习

  • 添加优先级(高/中/低)
  • 添加截止日期
  • 按优先级/截止日期排序
  • 搜索功能
  • 分类标签
  • 统计功能(每日完成数、完成率等)

项目4:词频统计

项目描述

统计一段文本中每个单词出现的次数。

知识点

  • 字符串操作
  • 字典
  • 列表
  • 排序
  • 文件操作

参考代码

import string
from collections import Counter
 
def count_words(text):
    """统计词频"""
    # 转小写
    text = text.lower()
 
    # 去除标点符号
    for punc in string.punctuation:
        text = text.replace(punc, " ")
 
    # 分割成单词
    words = text.split()
 
    # 统计词频
    word_counts = Counter(words)
 
    return word_counts
 
def print_top_words(word_counts, top_n=10):
    """打印出现次数最多的单词"""
    print(f"\n=== 词频统计(前{top_n}名)===")
    print(f"{'排名':<6}{'单词':<15}{'次数':<6}")
    print("-" * 30)
 
    for i, (word, count) in enumerate(word_counts.most_common(top_n), 1):
        print(f"{i:<6}{word:<15}{count:<6}")
 
def main():
    print("=== 词频统计工具 ===")
    print("1. 输入文本")
    print("2. 从文件读取")
 
    choice = input("请选择(1/2):")
 
    if choice == "1":
        text = input("请输入文本:\n")
    elif choice == "2":
        filename = input("请输入文件名:")
        try:
            with open(filename, "r", encoding="utf-8") as f:
                text = f.read()
        except FileNotFoundError:
            print(f"文件 {filename} 不存在")
            return
    else:
        print("无效的选择")
        return
 
    word_counts = count_words(text)
    print(f"\n总单词数:{sum(word_counts.values())}")
    print(f"不同单词数:{len(word_counts)}")
    print_top_words(word_counts)
 
if __name__ == "__main__":
    main()

扩展练习

  • 支持中文分词(需要 jieba 库)
  • 停用词过滤(排除 the, a, is 等无意义的词)
  • 生成词云图(需要 wordcloud 库)
  • 支持多个文件批量统计
  • 导出统计结果到 CSV 文件

项目5:石头剪刀布

项目描述

和电脑玩石头剪刀布游戏。

知识点

  • 随机数
  • 条件判断
  • 循环
  • 函数

参考代码

import random
 
def get_computer_choice():
    """电脑随机选择"""
    choices = ["石头", "剪刀", "布"]
    return random.choice(choices)
 
def get_winner(player, computer):
    """判断胜负"""
    if player == computer:
        return "平局"
 
    # 玩家赢的情况
    win_conditions = [
        ("石头", "剪刀"),
        ("剪刀", "布"),
        ("布", "石头")
    ]
 
    if (player, computer) in win_conditions:
        return "你赢了"
    else:
        return "你输了"
 
def rock_paper_scissors():
    print("=== 石头剪刀布 ===")
    print("规则:石头赢剪刀,剪刀赢布,布赢石头")
 
    wins = 0
    losses = 0
    draws = 0
 
    while True:
        print("\n请选择:")
        print("1. 石头")
        print("2. 剪刀")
        print("3. 布")
        print("0. 退出")
 
        choice = input("你的选择(0-3):")
 
        if choice == "0":
            print("\n=== 游戏结束 ===")
            print(f"胜:{wins} 负:{losses} 平:{draws}")
            total = wins + losses + draws
            if total > 0:
                print(f"胜率:{wins/total*100:.1f}%")
            break
 
        choices = {"1": "石头", "2": "剪刀", "3": "布"}
        if choice not in choices:
            print("无效的选择")
            continue
 
        player_choice = choices[choice]
        computer_choice = get_computer_choice()
 
        print(f"\n你出了:{player_choice}")
        print(f"电脑出了:{computer_choice}")
 
        result = get_winner(player_choice, computer_choice)
        print(f"结果:{result}")
 
        if result == "你赢了":
            wins += 1
        elif result == "你输了":
            losses += 1
        else:
            draws += 1
 
if __name__ == "__main__":
    rock_paper_scissors()

扩展练习

  • 增加更多选项(比如蜥蜴、史波克)
  • 多局制(比如三局两胜)
  • 电脑学习玩家习惯,提高胜率
  • 排行榜功能
  • 双人对战模式

🔗 相关章节


📝 我的笔记

在这里记录你的项目练习心得和改进想法

# 你的改进代码
 

✅ 本章检查清单

  • 完成猜数字游戏
  • 完成简易计算器
  • 完成待办事项管理
  • 完成词频统计
  • 完成石头剪刀布
  • 尝试至少一个扩展练习