第11章:Python实战项目 - 学以致用
◆ 📌 本章导读
学了这么多知识,是时候大展身手了!通过实战项目巩固所学,提升编程能力!
本章你将学会:
-
- ◆ ✅ 综合运用Python知识
-
- ◆ ✅ 项目架构设计思路
-
- ◆ ✅ 独立完成完整项目
-
- ◆ ✅ 解决实际问题的能力
-
预计学习时间:7-14天
前置知识:第10章 - 常用库精讲
~ ◆ ~
◆ 11.1 入门级项目
项目1:简易计算器
项目目标:实现支持加减乘除的计算器程序
核心知识:函数、流程控制、异常处理
defcalculator():
"""简易计算器"""
print("=" * 30)
print(" 简易计算器")
print("=" * 30)
while True:
try:
# 获取输入
num1 = float(input("\n请输入第一个数字:"))
operator = input("请输入运算符(+, -, *, /):")
num2 = float(input("请输入第二个数字:"))
# 计算
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("错误:除数不能为0!")
continue
result = num1 / num2
else:
print("错误:无效的运算符!")
continue
print(f"结果: {num1}{operator}{num2} = {result}")
# 询问是否继续
cont = input("\n是否继续?(y/n):")
if cont.lower() != 'y':
break
except ValueError:
print("错误:请输入有效的数字!")
print("\n感谢使用计算器!")
if __name__ == "__main__":
calculator()
~ ◆ ~
项目2:待办事项管理
项目目标:实现可以增删改查的待办事项系统
核心知识:列表、字典、文件操作
importjson
importos
TODO_FILE = "todos.json"
defload_todos():
"""加载待办事项"""
if os.path.exists(TODO_FILE):
with open(TODO_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
return []
defsave_todos(todos):
"""保存待办事项"""
with open(TODO_FILE, 'w', encoding='utf-8') as f:
json.dump(todos, f, ensure_ascii=False, indent=2)
defadd_todo(todos):
"""添加待办事项"""
title = input("请输入待办事项:")
todos.append({"title": title, "done": False})
save_todos(todos)
print("添加成功!")
defview_todos(todos):
"""查看待办事项"""
if not todos:
print("暂无待办事项")
return
print("\n" + "=" * 30)
for i, todo in enumerate(todos, 1):
status = "✓" if todo["done"] else "○"
print(f"{i}. [{status}] {todo['title']}")
print("=" * 30)
deftoggle_todo(todos):
"""标记完成/未完成"""
view_todos(todos)
try:
index = int(input("请输入要标记的序号:")) - 1
if 0 <= index < len(todos):
todos[index]["done"] = not todos[index]["done"]
save_todos(todos)
print("更新成功!")
else:
print("无效的序号!")
except ValueError:
print("请输入有效的数字!")
defmain():
"""主函数"""
todos = load_todos()
while True:
print("\n===== 待办事项管理 =====")
print("1. 查看所有待办")
print("2. 添加待办")
print("3. 标记完成/未完成")
print("4. 删除待办")
print("5. 退出")
choice = input("请选择操作:")
if choice == '1':
view_todos(todos)
elif choice == '2':
add_todo(todos)
elif choice == '3':
toggle_todo(todos)
elif choice == '4':
view_todos(todos)
try:
index = int(input("请输入要删除的序号:")) - 1
if 0 <= index < len(todos):
todos.pop(index)
save_todos(todos)
print("删除成功!")
except ValueError:
print("请输入有效的数字!")
elif choice == '5':
print("再见!")
break
else:
print("无效选择!")
if __name__ == "__main__":
main()
~ ◆ ~
◆ 11.2 进阶级项目
项目4:爬虫入门
项目目标:爬取网页数据并保存
核心知识:requests、BeautifulSoup、文件操作
importrequests
frombs4import BeautifulSoup
importcsv
importtime
defscrape_books():
"""爬取书籍信息"""
base_url = "http://books.toscrape.com/catalogue/page-{}.html"
all_books = []
for page in range(1, 3): # 爬取前2页
print(f"正在爬取第{page}页...")
response = requests.get(base_url.format(page))
soup = BeautifulSoup(response.text, 'html.parser')
books = soup.find_all('article', class_='product_pod')
for book in books:
title = book.h3.a['alt']
price = book.find('p', class_='price_color').text
rating = book.p['class'][1]
all_books.append({
'title': title,
'price': price,
'rating': rating
})
time.sleep(1) # 礼貌爬取
# 保存到CSV
with open('books.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['title', 'price', 'rating'])
writer.writeheader()
writer.writerows(all_books)
print(f"爬取完成!共{len(all_books)}本书籍")
if __name__ == "__main__":
scrape_books()
~ ◆ ~
项目5:数据分析报告生成
项目目标:读取数据,进行分析,生成报告
核心知识:pandas、matplotlib、文件操作
importpandasaspd
importmatplotlib.pyplotasplt
defanalyze_sales():
"""销售数据分析"""
# 模拟数据
data = {
'月份': ['1月', '2月', '3月', '4月', '5月', '6月'],
'销售额': [12000, 15000, 18000, 16000, 22000, 25000],
'成本': [8000, 9000, 11000, 10000, 13000, 15000]
}
df = pd.DataFrame(data)
# 计算利润
df['利润'] = df['销售额'] - df['成本']
df['利润率'] = (df['利润'] / df['销售额'] * 100).round(2)
# 打印报告
print("=" * 50)
print(" 销售分析报告")
print("=" * 50)
print(f"\n总销售额: {df['销售额'].sum()}元")
print(f"总成本: {df['成本'].sum()}元")
print(f"总利润: {df['利润'].sum()}元")
print(f"平均利润率: {df['利润率'].mean()}%")
print(f"\n最佳月份: {df.loc[df['利润'].idxmax(),'月份']}")
print(f"最佳利润: {df['利润'].max()}元")
# 生成图表
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.bar(df['月份'], df['销售额'], label='销售额')
plt.bar(df['月份'], df['成本'], label='成本')
plt.legend()
plt.title('月度销售与成本对比')
plt.subplot(1, 2, 2)
plt.plot(df['月份'], df['利润率'], marker='o', color='red')
plt.title('月度利润率趋势')
plt.tight_layout()
plt.savefig('sales_report.png')
print("\n报告图表已保存为sales_report.png")
if __name__ == "__main__":
analyze_sales()
~ ◆ ~
◆ 11.3 高级项目
项目7:简易Web应用
项目目标:使用Flask开发用户管理系统
核心知识:Flask、SQLite、HTML模板
fromflaskimport Flask, render_template, request, redirect, url_for
importsqlite3
app = Flask(__name__)
defget_db():
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
return conn
definit_db():
conn = get_db()
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL)''')
conn.commit()
conn.close()
@app.route('/')
defindex():
conn = get_db()
users = conn.execute('SELECT * FROM users').fetchall()
conn.close()
return render_template('index.html', users=users)
@app.route('/add', methods=['POST'])
defadd_user():
name = request.form['name']
email = request.form['email']
conn = get_db()
conn.execute('INSERT INTO users (name, email) VALUES (?, ?)', (name, email))
conn.commit()
conn.close()
return redirect(url_for('index'))
@app.route('/delete/<int:user_id>')
defdelete_user(user_id):
conn = get_db()
conn.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit()
conn.close()
return redirect(url_for('index'))
if __name__ == '__main__':
init_db()
app.run(debug=True)
~ ◆ ~
◆ 📝 本章小结
项目经验总结
✅ 入门项目:巩固基础语法和数据结构
✅ 进阶项目:学习第三方库和API使用
✅ 高级项目:掌握Web开发和数据库操作
✅ 项目架构:从需求分析到功能实现的完整流程
🎯 下一步学习方向
-
- ◆ 深入学习框架(Django、FastAPI)
-
- ◆ 学习前端技术(HTML/CSS/JavaScript)
-
- ◆ 探索人工智能(Machine Learning)
-
- ◆ 参与开源项目
-
- ◆ 构建个人作品集
-
~ ◆ ~
◆ 💬 互动环节
你完成了哪个项目?遇到了什么困难?
欢迎在留言区分享你的学习成果!
~ ◆ ~
学习建议:实践是最好的老师!尝试修改项目代码,添加新功能,不断优化!