包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取!】
作为CSDN技术博主,我将为你设计10个Python脚本,从基础到高级,逐步提升你的Python编程能力。每个脚本都配有详细解释和应用场景分析。
脚本1:Python基础 - 温度转换器
# 摄氏度和华氏度互相转换
def temperature_converter():
print("温度转换器")
print("1. 摄氏度转华氏度")
print("2. 华氏度转摄氏度")
choice = input("请选择转换类型(1/2): ")
if choice == '1':
celsius = float(input("请输入摄氏度: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit:.2f}°F")
elif choice == '2':
fahrenheit = float(input("请输入华氏度: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}°F = {celsius:.2f}°C")
else:
print("无效输入")
if __name__ == "__main__":
temperature_converter()
学习要点:基础输入输出、条件判断、浮点数运算、字符串格式化
脚本2:数据结构 - 简易通讯录
# 使用字典实现简易通讯录
def contact_book():
contacts = {}
while True:
print("\n简易通讯录")
print("1. 添加联系人")
print("2. 查找联系人")
print("3. 删除联系人")
print("4. 显示所有联系人")
print("5. 退出")
choice = input("请选择操作(1-5): ")
if choice == '1':
name = input("输入姓名: ")
phone = input("输入电话: ")
contacts[name] = phone
print(f"{name} 已添加到通讯录")
elif choice == '2':
name = input("输入要查找的姓名: ")
print(f"{name}: {contacts.get(name, '未找到')}")
elif choice == '3':
name = input("输入要删除的姓名: ")
if name in contacts:
del contacts[name]
print(f"{name} 已删除")
else:
print("联系人不存在")
elif choice == '4':
print("\n所有联系人:")
for name, phone in contacts.items():
print(f"{name}: {phone}")
elif choice == '5':
print("退出通讯录")
break
else:
print("无效输入")
if __name__ == "__main__":
contact_book()
学习要点:字典操作、循环控制、用户交互设计
脚本3:文件操作 - 日志分析器
# 分析日志文件,统计错误和警告数量
import re
def log_analyzer():
log_file = input("请输入日志文件路径: ")
error_count = 0
warning_count = 0
try:
with open(log_file, 'r') as file:
for line in file:
if re.search(r'ERROR', line, re.IGNORECASE):
error_count += 1
elif re.search(r'WARNING', line, re.IGNORECASE):
warning_count += 1
print(f"分析结果:")
print(f"错误(ERROR)数量: {error_count}")
print(f"警告(WARNING)数量: {warning_count}")
print(f"总计: {error_count + warning_count}")
except FileNotFoundError:
print("文件未找到,请检查路径")
except Exception as e:
print(f"发生错误: {str(e)}")
if __name__ == "__main__":
log_analyzer()
学习要点:文件操作、正则表达式、异常处理
脚本4:面向对象 - 银行账户系统
# 简单的银行账户类实现
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self.balance = initial_balance
self.transactions = []
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transactions.append(f"存款: +{amount}")
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
self.transactions.append(f"取款: -{amount}")
return True
return False
def get_balance(self):
return self.balance
def get_transactions(self):
return self.transactions
def __str__(self):
return f"账户持有人: {self.account_holder}, 余额: {self.balance}"
def bank_system():
accounts = {}
while True:
print("\n简易银行系统")
print("1. 创建账户")
print("2. 存款")
print("3. 取款")
print("4. 查询余额")
print("5. 查询交易记录")
print("6. 退出")
choice = input("请选择操作(1-6): ")
if choice == '1':
name = input("输入账户持有人姓名: ")
initial = float(input("输入初始金额: "))
accounts[name] = BankAccount(name, initial)
print(f"账户创建成功: {accounts[name]}")
elif choice == '2':
name = input("输入账户持有人姓名: ")
if name in accounts:
amount = float(input("输入存款金额: "))
if accounts[name].deposit(amount):
print("存款成功")
else:
print("存款金额必须大于0")
else:
print("账户不存在")
elif choice == '3':
name = input("输入账户持有人姓名: ")
if name in accounts:
amount = float(input("输入取款金额: "))
if accounts[name].withdraw(amount):
print("取款成功")
else:
print("取款金额无效或余额不足")
else:
print("账户不存在")
elif choice == '4':
name = input("输入账户持有人姓名: ")
if name in accounts:
print(f"当前余额: {accounts[name].get_balance()}")
else:
print("账户不存在")
elif choice == '5':
name = input("输入账户持有人姓名: ")
if name in accounts:
print("交易记录:")
for trans in accounts[name].get_transactions():
print(trans)
else:
print("账户不存在")
elif choice == '6':
print("退出银行系统")
break
else:
print("无效输入")
if __name__ == "__main__":
bank_system()
学习要点:类与对象、封装、方法设计、对象管理
脚本5:网络请求 - 天气查询工具
# 使用API查询天气信息
import requests
import json
def weather_app():
API_KEY = "YOUR_API_KEY" # 替换为你的API密钥
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
city = input("输入城市名称: ")
try:
params = {
'q': city,
'appid': API_KEY,
'units': 'metric',
'lang': 'zh_cn'
}
response = requests.get(BASE_URL, params=params)
data = response.json()
if response.status_code == 200:
print(f"\n{city}的天气信息:")
print(f"温度: {data['main']['temp']}°C")
print(f"天气状况: {data['weather'][0]['description']}")
print(f"湿度: {data['main']['humidity']}%")
print(f"风速: {data['wind']['speed']} m/s")
else:
print(f"获取天气信息失败: {data.get('message', '未知错误')}")
except requests.exceptions.RequestException as e:
print(f"网络请求错误: {str(e)}")
except json.JSONDecodeError:
print("解析响应数据失败")
except KeyError:
print("获取天气数据时发生错误")
if __name__ == "__main__":
weather_app()
学习要点:API调用、HTTP请求、JSON数据处理、异常处理
脚本6:多线程 - 网页下载器
# 多线程下载多个网页内容
import threading
import requests
import time
def download_page(url, results, index):
try:
response = requests.get(url, timeout=10)
results[index] = {
'url': url,
'status': response.status_code,
'length': len(response.text),
'time': time.time()
}
except Exception as e:
results[index] = {
'url': url,
'error': str(e)
}
def multi_downloader():
urls = [
'https://www.python.org',
'https://www.google.com',
'https://www.github.com',
'https://www.example.com',
'https://www.baidu.com'
]
results = [None] * len(urls)
threads = []
start_time = time.time()
for i, url in enumerate(urls):
thread = threading.Thread(
target=download_page,
args=(url, results, i)
)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("\n下载结果:")
for result in results:
if 'error' in result:
print(f"{result['url']} - 错误: {result['error']}")
else:
print(f"{result['url']} - 状态: {result['status']}, "
f"大小: {result['length']}字节, "
f"耗时: {time.time() - start_time:.2f}秒")
if __name__ == "__main__":
multi_downloader()
学习要点:多线程编程、线程同步、性能优化
脚本7:数据处理 - CSV分析工具
# 分析CSV文件数据
import csv
from collections import defaultdict
def csv_analyzer():
file_path = input("请输入CSV文件路径: ")
try:
with open(file_path, mode='r', encoding='utf-8') as file:
reader = csv.DictReader(file)
if not reader.fieldnames:
print("CSV文件为空或格式不正确")
return
print(f"\n可用字段: {', '.join(reader.fieldnames)}")
numeric_fields = []
# 检测数值型字段
first_row = next(reader, None)
if first_row:
for field in reader.fieldnames:
try:
float(first_row[field])
numeric_fields.append(field)
except (ValueError, TypeError):
pass
print(f"\n数值型字段: {', '.join(numeric_fields) if numeric_fields else '无'}")
# 重置文件指针
file.seek(0)
next(reader) # 跳过标题行
# 统计数据
stats = defaultdict(list)
row_count = 0
for row in reader:
row_count += 1
for field in numeric_fields:
try:
value = float(row[field])
stats[field].append(value)
except (ValueError, TypeError):
pass
print(f"\n分析结果 (共 {row_count} 行数据):")
for field in numeric_fields:
values = stats[field]
if values:
print(f"\n字段: {field}")
print(f" 平均值: {sum(values)/len(values):.2f}")
print(f" 最大值: {max(values):.2f}")
print(f" 最小值: {min(values):.2f}")
print(f" 中位数: {sorted(values)[len(values)//2]:.2f}")
else:
print(f"\n字段: {field} - 无有效数据")
except FileNotFoundError:
print("文件未找到,请检查路径")
except Exception as e:
print(f"分析CSV文件时出错: {str(e)}")
if __name__ == "__main__":
csv_analyzer()
学习要点:CSV处理、数据分析、统计计算、异常处理
脚本8:GUI编程 - 简易画图板
# 使用tkinter创建简易画图程序
import tkinter as tk
from tkinter import colorchooser
class DrawingApp:
def __init__(self, root):
self.root = root
self.root.title("简易画图板")
self.canvas = tk.Canvas(root, bg="white", width=800, height=600)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.setup_toolbar()
self.setup_bindings()
self.last_x = None
self.last_y = None
self.color = "black"
self.line_width = 2
self.drawing_tool = "pen"
def setup_toolbar(self):
toolbar = tk.Frame(self.root)
toolbar.pack(fill=tk.X)
# 工具按钮
tk.Button(toolbar, text="画笔", command=lambda: self.set_tool("pen")).pack(side=tk.LEFT)
tk.Button(toolbar, text="直线", command=lambda: self.set_tool("line")).pack(side=tk.LEFT)
tk.Button(toolbar, text="矩形", command=lambda: self.set_tool("rect")).pack(side=tk.LEFT)
tk.Button(toolbar, text="椭圆", command=lambda: self.set_tool("oval")).pack(side=tk.LEFT)
tk.Button(toolbar, text="橡皮", command=lambda: self.set_tool("eraser")).pack(side=tk.LEFT)
tk.Button(toolbar, text="清空", command=self.clear_canvas).pack(side=tk.LEFT)
# 颜色选择
tk.Button(toolbar, text="颜色", command=self.choose_color).pack(side=tk.LEFT)
self.color_display = tk.Label(toolbar, bg=self.color, width=2, relief=tk.SUNKEN)
self.color_display.pack(side=tk.LEFT, padx=5)
# 线宽选择
tk.Label(toolbar, text="线宽:").pack(side=tk.LEFT)
self.width_slider = tk.Scale(toolbar, from_=1, to=20, orient=tk.HORIZONTAL,
command=self.set_width)
self.width_slider.set(self.line_width)
self.width_slider.pack(side=tk.LEFT)
def setup_bindings(self):
self.canvas.bind("<Button-1>", self.start_draw)
self.canvas.bind("<B1-Motion>", self.draw)
self.canvas.bind("<ButtonRelease-1>", self.end_draw)
def set_tool(self, tool):
self.drawing_tool = tool
def choose_color(self):
color = colorchooser.askcolor()[1]
if color:
self.color = color
self.color_display.config(bg=color)
def set_width(self, value):
self.line_width = int(value)
def clear_canvas(self):
self.canvas.delete("all")
def start_draw(self, event):
self.last_x = event.x
self.last_y = event.y
if self.drawing_tool in ["line", "rect", "oval"]:
self.start_x = event.x
self.start_y = event.y
self.temp_item = None
def draw(self, event):
x, y = event.x, event.y
if self.drawing_tool == "pen":
if self.last_x and self.last_y:
self.canvas.create_line(self.last_x, self.last_y, x, y,
fill=self.color, width=self.line_width)
self.last_x = x
self.last_y = y
elif self.drawing_tool == "eraser":
if self.last_x and self.last_y:
self.canvas.create_line(self.last_x, self.last_y, x, y,
fill="white", width=self.line_width*2)
self.last_x = x
self.last_y = y
elif self.drawing_tool in ["line", "rect", "oval"]:
if self.temp_item:
self.canvas.delete(self.temp_item)
if self.drawing_tool == "line":
self.temp_item = self.canvas.create_line(
self.start_x, self.start_y, x, y,
fill=self.color, width=self.line_width)
elif self.drawing_tool == "rect":
self.temp_item = self.canvas.create_rectangle(
self.start_x, self.start_y, x, y,
outline=self.color, width=self.line_width)
elif self.drawing_tool == "oval":
self.temp_item = self.canvas.create_oval(
self.start_x, self.start_y, x, y,
outline=self.color, width=self.line_width)
def end_draw(self, event):
if self.drawing_tool in ["line", "rect", "oval"] and hasattr(self, 'temp_item'):
if self.temp_item:
self.canvas.itemconfig(self.temp_item, tags=("permanent",))
del self.temp_item
self.last_x = None
self.last_y = None
if __name__ == "__main__":
root = tk.Tk()
app = DrawingApp(root)
root.mainloop()
学习要点:GUI编程、事件处理、绘图功能、面向对象设计
脚本9:数据库 - 学生管理系统
# 使用SQLite数据库的学生管理系统
import sqlite3
from contextlib import closing
class StudentManager:
def __init__(self, db_name="students.db"):
self.db_name = db_name
self.init_db()
def init_db(self):
with closing(sqlite3.connect(self.db_name)) as conn:
with conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
gender TEXT,
major TEXT,
grade REAL
)
""")
def add_student(self, name, age, gender, major, grade):
with closing(sqlite3.connect(self.db_name)) as conn:
with conn:
conn.execute("""
INSERT INTO students (name, age, gender, major, grade)
VALUES (?, ?, ?, ?, ?)
""", (name, age, gender, major, grade))
def delete_student(self, student_id):
with closing(sqlite3.connect(self.db_name)) as conn:
with conn:
conn.execute("DELETE FROM students WHERE id = ?", (student_id,))
def update_student(self, student_id, **kwargs):
if not kwargs:
return False
set_clause = ", ".join(f"{k} = ?" for k in kwargs.keys())
values = list(kwargs.values())
values.append(student_id)
with closing(sqlite3.connect(self.db_name)) as conn:
with conn:
conn.execute(f"""
UPDATE students
SET {set_clause}
WHERE id = ?
""", values)
return True
def get_student(self, student_id):
with closing(sqlite3.connect(self.db_name)) as conn:
cursor = conn.execute("SELECT * FROM students WHERE id = ?", (student_id,))
return cursor.fetchone()
def list_students(self, filter_by=None, filter_value=None):
query = "SELECT * FROM students"
params = ()
if filter_by and filter_value:
query += f" WHERE {filter_by} = ?"
params = (filter_value,)
with closing(sqlite3.connect(self.db_name)) as conn:
cursor = conn.execute(query, params)
return cursor.fetchall()
def get_statistics(self):
with closing(sqlite3.connect(self.db_name)) as conn:
cursor = conn.execute("""
SELECT
COUNT(*) as total,
AVG(grade) as avg_grade,
MAX(grade) as max_grade,
MIN(grade) as min_grade
FROM students
""")
return cursor.fetchone()
def student_system():
manager = StudentManager()
while True:
print("\n学生管理系统")
print("1. 添加学生")
print("2. 删除学生")
print("3. 更新学生信息")
print("4. 查询学生")
print("5. 列出所有学生")
print("6. 按条件筛选学生")
print("7. 查看统计信息")
print("8. 退出")
choice = input("请选择操作(1-8): ")
if choice == '1':
name = input("姓名: ")
age = int(input("年龄: "))
gender = input("性别(M/F): ").upper()
major = input("专业: ")
grade = float(input("成绩: "))
manager.add_student(name, age, gender, major, grade)
print("学生添加成功")
elif choice == '2':
student_id = int(input("输入要删除的学生ID: "))
if manager.get_student(student_id):
manager.delete_student(student_id)
print("学生删除成功")
else:
print("学生不存在")
elif choice == '3':
student_id = int(input("输入要更新的学生ID: "))
student = manager.get_student(student_id)
if not student:
print("学生不存在")
continue
print("当前信息:")
print(f"1. 姓名: {student[1]}")
print(f"2. 年龄: {student[2]}")
print(f"3. 性别: {student[3]}")
print(f"4. 专业: {student[4]}")
print(f"5. 成绩: {student[5]}")
fields = input("选择要更新的字段(1-5, 多个用逗号分隔): ").split(',')
updates = {}
for field in fields:
field = field.strip()
if field == '1':
updates['name'] = input("新姓名: ")
elif field == '2':
updates['age'] = int(input("新年龄: "))
elif field == '3':
updates['gender'] = input("新性别(M/F): ").upper()
elif field == '4':
updates['major'] = input("新专业: ")
elif field == '5':
updates['grade'] = float(input("新成绩: "))
if updates:
manager.update_student(student_id, **updates)
print("学生信息更新成功")
elif choice == '4':
student_id = int(input("输入要查询的学生ID: "))
student = manager.get_student(student_id)
if student:
print("\n学生信息:")
print(f"ID: {student[0]}")
print(f"姓名: {student[1]}")
print(f"年龄: {student[2]}")
print(f"性别: {student[3]}")
print(f"专业: {student[4]}")
print(f"成绩: {student[5]}")
else:
print("学生不存在")
elif choice == '5':
students = manager.list_students()
print("\n所有学生:")
for student in students:
print(f"{student[0]}: {student[1]}, {student[2]}岁, {student[4]}专业, 成绩: {student[5]}")
elif choice == '6':
print("筛选条件:")
print("1. 按专业")
print("2. 按性别")
print("3. 按年龄范围")
filter_choice = input("选择筛选方式(1-3): ")
if filter_choice == '1':
major = input("输入专业名称: ")
students = manager.list_students("major", major)
elif filter_choice == '2':
gender = input("输入性别(M/F): ").upper()
students = manager.list_students("gender", gender)
elif filter_choice == '3':
min_age = int(input("最小年龄: "))
max_age = int(input("最大年龄: "))
students = [s for s in manager.list_students()
if min_age <= s[2] <= max_age]
else:
print("无效选择")
continue
print("\n筛选结果:")
for student in students:
print(f"{student[0]}: {student[1]}, {student[2]}岁, {student[4]}专业, 成绩: {student[5]}")
elif choice == '7':
total, avg_grade, max_grade, min_grade = manager.get_statistics()
print("\n统计信息:")
print(f"学生总数: {total}")
print(f"平均成绩: {avg_grade:.2f}")
print(f"最高成绩: {max_grade}")
print(f"最低成绩: {min_grade}")
elif choice == '8':
print("退出系统")
break
else:
print("无效输入")
if __name__ == "__main__":
student_system()
学习要点:SQLite数据库操作、CRUD实现、上下文管理器、数据统计
脚本10:Web开发 - Flask博客系统
# 使用Flask框架的简易博客系统
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
from contextlib import closing
import os
app = Flask(__name__)
app.secret_key = 'your_secret_key_here'
DATABASE = 'blog.db'
def init_db():
with closing(sqlite3.connect(DATABASE)) as conn:
with conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
author TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(post_id) REFERENCES posts(id)
)
""")
def get_db():
db = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db
@app.route('/')
def index():
db = get_db()
posts = db.execute('SELECT * FROM posts ORDER BY created_at DESC').fetchall()
db.close()
return render_template('index.html', posts=posts)
@app.route('/post/<int:post_id>')
def show_post(post_id):
db = get_db()
post = db.execute('SELECT * FROM posts WHERE id = ?', (post_id,)).fetchone()
comments = db.execute('SELECT * FROM comments WHERE post_id = ? ORDER BY created_at',
(post_id,)).fetchall()
db.close()
if post is None:
flash('文章不存在')
return redirect(url_for('index'))
return render_template('post.html', post=post, comments=comments)
@app.route('/create', methods=['GET', 'POST'])
def create_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if not title or not content:
flash('标题和内容不能为空')
else:
db = get_db()
db.execute('INSERT INTO posts (title, content) VALUES (?, ?)',
(title, content))
db.commit()
db.close()
flash('文章创建成功')
return redirect(url_for('index'))
return render_template('create.html')
@app.route('/post/<int:post_id>/comment', methods=['POST'])
def add_comment(post_id):
author = request.form['author']
content = request.form['content']
if not author or not content:
flash('昵称和评论内容不能为空')
else:
db = get_db()
db.execute('INSERT INTO comments (post_id, author, content) VALUES (?, ?, ?)',
(post_id, author, content))
db.commit()
db.close()
flash('评论添加成功')
return redirect(url_for('show_post', post_id=post_id))
@app.route('/post/<int:post_id>/delete', methods=['POST'])
def delete_post(post_id):
db = get_db()
db.execute('DELETE FROM posts WHERE id = ?', (post_id,))
db.execute('DELETE FROM comments WHERE post_id = ?', (post_id,))
db.commit()
db.close()
flash('文章删除成功')
return redirect(url_for('index'))
if __name__ == '__main__':
if not os.path.exists(DATABASE):
init_db()
app.run(debug=True)
模板文件 (templates/index.html):
<!DOCTYPE html>
<html>
<head>
<title>我的博客</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
.post { margin-bottom: 30px; border-bottom: 1px solid #eee; padding-bottom: 20px; }
.post h2 a { color: #333; text-decoration: none; }
.post-meta { color: #666; font-size: 0.9em; }
.flash-message { padding: 10px; margin: 10px 0; background: #f0f0f0; }
</style>
</head>
<body>
<h1>我的博客</h1>
<a href="{{ url_for('create_post') }}">写新文章</a>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash-message">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
{% for post in posts %}
<div class="post">
<h2><a href="{{ url_for('show_post', post_id=post['id']) }}">{{ post['title'] }}</a></h2>
<div class="post-meta">发布于 {{ post['created_at'] }}</div>
<p>{{ post['content'][:200] }}{% if post['content']|length > 200 %}...{% endif %}</p>
<a href="{{ url_for('show_post', post_id=post['id']) }}">阅读更多</a>
</div>
{% endfor %}
</body>
</html>
模板文件 (templates/post.html):
<!DOCTYPE html>
<html>
<head>
<title>{{ post['title'] }}</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
.post { margin-bottom: 30px; }
.post-meta { color: #666; font-size: 0.9em; }
.comments { margin-top: 40px; }
.comment { margin-bottom: 20px; padding: 10px; background: #f9f9f9; }
.comment-meta { color: #666; font-size: 0.8em; }
.flash-message { padding: 10px; margin: 10px 0; background: #f0f0f0; }
form { margin-top: 20px; }
textarea { width: 100%; height: 100px; }
</style>
</head>
<body>
<a href="{{ url_for('index') }}">返回首页</a>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash-message">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="post">
<h1>{{ post['title'] }}</h1>
<div class="post-meta">发布于 {{ post['created_at'] }}</div>
<p>{{ post['content'] }}</p>
<form action="{{ url_for('delete_post', post_id=post['id']) }}" method="post">
<input type="submit" value="删除文章" onclick="return confirm('确定删除吗?')">
</form>
</div>
<div class="comments">
<h3>评论 ({{ comments|length }})</h3>
{% for comment in comments %}
<div class="comment">
<div class="comment-meta">
{{ comment['author'] }} 发布于 {{ comment['created_at'] }}
</div>
<p>{{ comment['content'] }}</p>
</div>
{% endfor %}
<h3>发表评论</h3>
<form action="{{ url_for('add_comment', post_id=post['id']) }}" method="post">
<div>
<label for="author">昵称:</label>
<input type="text" id="author" name="author" required>
</div>
<div>
<label for="content">评论内容:</label>
<textarea id="content" name="content" required></textarea>
</div>
<input type="submit" value="提交评论">
</form>
</div>
</body>
</html>
模板文件 (templates/create.html):
<!DOCTYPE html>
<html>
<head>
<title>写新文章</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
form div { margin-bottom: 10px; }
input[type="text"], textarea { width: 100%; }
textarea { height: 300px; }
.flash-message { padding: 10px; margin: 10px 0; background: #f0f0f0; }
</style>
</head>
<body>
<h1>写新文章</h1>
<a href="{{ url_for('index') }}">返回首页</a>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash-message">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<form action="{{ url_for('create_post') }}" method="post">
<div>
<label for="title">标题:</label>
<input type="text" id="title" name="title" required>
</div>
<div>
<label for="content">内容:</label>
<textarea id="content" name="content" required></textarea>
</div>
<input type="submit" value="发布文章">
</form>
</body>
</html>
学习要点:Flask框架、Web开发、数据库集成、模板渲染、表单处理
总结
这10个Python脚本涵盖了从基础到高级的多个方面:
1.基础语法和流程控制
2.数据结构应用
3.文件操作和正则表达式
4.面向对象编程
5.网络请求和API调用
6.多线程编程
7.数据处理和分析
8.GUI应用程序开发
9.数据库操作
10.Web开发框架
每个脚本都设计为实用且具有教育意义,通过实际项目学习Python是最有效的方式。建议你从第一个脚本开始,逐步完成所有项目,并在每个项目基础上进行扩展和改进,这样可以真正掌握Python编程的精髓。
👉Python学习路线汇总👈
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
👉Python必备开发工具👈
👉实战案例👈
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
👉Python副业兼职路线&方法👈
学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。