Python
11 实战小项目
猜数字 → 记账本 → 背单词
- Python
- 入门
目标:把前十章串起来,完整做出三个由易到难的小程序。强烈建议不看答案先自己写,写不出再看思路。
项目一:猜数字游戏(综合:循环 + 条件 + 输入)
需求:程序随机定一个 1~100 的答案,用户反复猜,提示大了/小了,猜中报告用了几次。
新知识只需要一行——随机数:
import random
answer = random.randint(1, 100) # 1~100 之间随机整数(两头都包含)
思路:while True 循环里 input → int() → 三分支判断(大/小/中,中则 break),用变量 count 记次数。
参考实现
import random
def main():
answer = random.randint(1, 100)
count = 0
print("我想好了一个 1~100 的数字,猜猜看!")
while True:
try:
guess = int(input("你的猜测:"))
except ValueError:
print("请输入数字!")
continue
count += 1
if guess > answer:
print("大了")
elif guess < answer:
print("小了")
else:
print(f"🎉 猜对了!用了 {count} 次")
break
main()
项目二:记账本(综合:字典列表 + JSON + 菜单循环)
需求:终端记账程序,支持:1 记一笔 2 查看全部 3 统计 0 退出;账目存 JSON 文件,重启不丢。
每笔账目的结构(字典):
{"item": "午饭", "amount": 25.0, "type": "支出"}
思路:
- 启动时读
ledger.json(不存在就从空列表开始)——第 10 章的 try/except FileNotFoundError。 while True菜单循环,按输入分支。- 记账就往列表
append字典,然后立刻存盘。 - 统计就循环累加收入/支出。
参考实现
import json
from pathlib import Path
LEDGER = Path("ledger.json")
def load():
try:
return json.loads(LEDGER.read_text(encoding="utf-8"))
except FileNotFoundError:
return []
def save(records):
LEDGER.write_text(
json.dumps(records, ensure_ascii=False, indent=2),
encoding="utf-8",
)
def add_record(records):
item = input("事项:")
amount = float(input("金额:"))
kind = input("类型(收入/支出):")
records.append({"item": item, "amount": amount, "type": kind})
save(records)
print("已记录 ✔")
def show_all(records):
if not records:
print("还没有账目")
return
for r in records:
print(f"{r['item']}:{r['amount']} 元({r['type']})")
def show_summary(records):
income = sum(r["amount"] for r in records if r["type"] == "收入")
outcome = sum(r["amount"] for r in records if r["type"] == "支出")
print(f"收入 {income:.2f},支出 {outcome:.2f},结余 {income - outcome:.2f}")
def main():
records = load()
while True:
print("\n== 记账本 ==\n1 记一笔 2 查看全部 3 统计 0 退出")
choice = input("请选择:")
if choice == "1":
add_record(records)
elif choice == "2":
show_all(records)
elif choice == "3":
show_summary(records)
elif choice == "0":
print("再见,账目已保存")
break
else:
print("没有这个选项")
main()
(sum(... for ...) 这种写法叫生成器表达式,是「循环累加」的一行版,等价于你手写的 total 循环。)
项目三:背单词(综合:字典 + 文件 + 随机抽题)
需求:
- 词库存在
words.json:[{"word": "apple", "meaning": "苹果"}, ...] - 每轮随机抽一个词,用户答中文意思,答对 +1 分,答错显示正确答案
- 输 q 退出并打印本次成绩;支持「添加新单词」
思路:结构同记账本(load/save/菜单),核心循环换成「随机抽词 → 对答案」。判对用 .strip() 处理输入两端空格。
参考实现
import json
import random
from pathlib import Path
BANK = Path("words.json")
def load():
try:
return json.loads(BANK.read_text(encoding="utf-8"))
except FileNotFoundError:
return []
def save(words):
BANK.write_text(json.dumps(words, ensure_ascii=False, indent=2),
encoding="utf-8")
def quiz(words):
score = 0
total = 0
while True:
card = random.choice(words)
answer = input(f"{card['word']} 是什么意思?(q 退出)").strip()
if answer == "q":
break
total += 1
if answer == card["meaning"]:
score += 1
print("✅ 正确!")
else:
print(f"❌ 正确答案:{card['meaning']}")
print(f"本次成绩:{score}/{total}")
def add_word(words):
word = input("英文:").strip()
meaning = input("中文:").strip()
words.append({"word": word, "meaning": meaning})
save(words)
print("已添加 ✔")
def main():
words = load()
if not words:
print("词库为空,先添加几个单词")
return
while True:
print("\n== 背单词 ==\n1 开始背 2 添加单词 0 退出")
choice = input("请选择:")
if choice == "1":
quiz(words)
elif choice == "2":
add_word(words)
elif choice == "0":
break
main()
做完这三个项目,你已经具备
- 变量、类型、输入输出的熟练使用
- 分支、循环组织程序流程
- 列表/字典/字符串管理数据
- 函数拆分模块,类的基本认识
- 文件 + JSON 让数据持久化
- 异常处理让程序健壮
这就是「会编程」的门槛内测——下一步往哪走,看 12-下一步怎么走。
加分挑战(可选)
- 记账本加「删除某笔」「按月份筛选」。
- 背单词加「答错的词优先再考」(错题本列表,抽题时 70% 概率从错题里抽)。
- 猜数字加难度选择(简单 1
50 十次机会 / 困难 1200 七次机会)。