欢迎来到Python源代码实例网站。本页汇集大量真实可运行的Python编程案例,覆盖从基础语法到高级应用的完整知识体系。无论您是编程新手还是希望提升实战能力的开发者,这里都能为您提供清晰、详实、可直接复用的代码示例。
我们深知:学习编程的核心在于“动手实践”,而非单纯阅读理论。因此,每个案例均经过实际测试验证,确保在Python 3.8+版本中可直接运行,同时附带关键步骤说明、常见问题提醒与扩展思考点,助您真正掌握编程思维与工程化能力。
本项目由 xservx.com 团队精心维护,内容持续更新。所有代码均遵循PEP 8规范,注重可读性与可维护性,适合用于自学、教学、项目参考及技术分享。
扎实掌握基础是进阶的前提。以下精选高频、易错、易混淆的基础知识点,通过可运行实例直观展示其用法与陷阱。
列表推导式简洁高效,但可能占用较多内存;生成器表达式按需计算,节省内存但需迭代消费:
# 列表推导式:一次性生成所有元素(占用内存)
squares_list = [x**2 for x in range(1000000)]
# 生成器表达式:惰性求值,节省内存
squares_gen = (x**2 for x in range(1000000))
# 实际使用时:生成器需迭代
# sum(squares_gen) → 按需计算,不存储中间结果
# sum(squares_list) → 先生成完整列表再求和,内存开销大
⚠️ 注意:生成器只能遍历一次,遍历后即耗尽。若需多次使用,请转为列表或重新创建。
Python中所有参数传递均为“对象引用传递”,但行为因对象是否可变而异:
def modify_list(lst):
lst.append(4) # 修改原列表(可变对象)
def modify_int(x):
x += 1 # 仅修改局部变量(不可变对象)
a = [1, 2, 3]
b = 5
modify_list(a)
modify_int(b)
print(a) # → [1, 2, 3, 4]
print(b) # → 5(未改变)
💡 常见误区:误以为Python是“值传递”或“引用传递”,实为“对象引用传递”,关键在于对象自身是否可变。
通过实现 __enter__ 和 __exit__ 方法,可为任意对象提供资源自动管理能力:
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
self.end = time.time()
print(f"执行耗时:{self.end - self.start:.4f}秒")
# 使用示例
with Timer():
total = sum(i**2 for i in range(10000000))
该模式广泛用于文件操作(with open(...))、数据库连接、线程锁等场景,确保资源可靠释放。
基于Flask和FastAPI构建轻量级Web应用,涵盖路由设计、请求处理、模板渲染、API开发等核心环节。
from flask import Flask, request, jsonify
app = Flask(__name__)
# 模拟数据库
POSTS = [{"id": i, "title": f"文章 {i}", "content": f"内容 {i}..."} for i in range(1, 101)]
@app.route("/api/posts")
def get_posts():
page = int(request.args.get("page", 1))
per_page = int(request.args.get("per_page", 10))
start = (page - 1) * per_page
end = start + per_page
data = POSTS[start:end]
return jsonify({
"data": data,
"total": len(POSTS),
"page": page,
"per_page": per_page,
"has_next": end < len(POSTS)
})
if __name__ == "__main__":
app.run(debug=True)
📌 延伸建议:实际项目中应使用数据库(如SQLite/PostgreSQL)替代内存列表;引入ORM(如SQLAlchemy)提升可维护性;增加分页缓存优化性能。
from fastapi import FastAPI, File, UploadFile, Form
from pydantic import BaseModel, Field
from typing import List
app = FastAPI()
class FileMeta(BaseModel):
filename: str = Field(..., max_length=100)
size: int = Field(gt=0, description="文件大小(字节)")
@app.post("/upload/")
async def upload_file(
file: UploadFile = File(...),
description: str = Form(default="")
):
content = await file.read()
meta = FileMeta(filename=file.filename, size=len(content))
return {
"meta": meta,
"description": description,
"preview": content[:50].decode("utf-8", errors="ignore")
}
💡 优势:FastAPI自动根据Pydantic模型生成交互式API文档(Swagger UI),极大提升前后端协作效率。
{# templates/index.html #}
{{ title }}
{{ title }}
{% for post in posts %}
- {{ post.title }}
{% endfor %}
后端渲染逻辑:
from flask import render_template
@app.route("/")
def index():
return render_template("index.html",
title="博客首页",
posts=POSTS[:5])
📌 安全提示:Jinja2模板引擎默认对变量进行HTML转义,防止XSS攻击;如需渲染原始HTML,请用 | safe 过滤器(需确保内容可信)。
结合NumPy、Pandas、Matplotlib,完成从数据清洗、统计分析到可视化的全流程实战。
import pandas as pd
import numpy as np
df = pd.DataFrame({
"A": [1, 2, np.nan, 4],
"B": [5, np.nan, 7, 8],
"C": [10, 20, 30, 40]
})
# 方法1:删除含缺失值的行
df_drop = df.dropna()
# 方法2:用均值填充(适用于数值型)
df_fill_mean = df.fillna(df.mean())
# 方法3:按列指定不同填充策略
df_strategy = df.fillna({"A": df["A"].median(), "B": 0})
# 方法4:前向填充(时间序列常用)
df_ffill = df.ffill()
💡 策略选择原则:缺失比例<5%可删除;>20%需谨慎填充;时间序列优先前向/后向填充;分类变量可用众数填充。
import seaborn as sns
# 加载示例数据集
tips = sns.load_dataset("tips")
# 构建透视表:按性别和是否吸烟分组,统计平均账单与小费
pivot = tips.pivot_table(
values=["total_bill", "tip"],
index=["sex", "smoker"],
aggfunc={"total_bill": ["mean", "std"], "tip": "mean"}
)
print(pivot)
📌 输出结构为多级列索引,可进一步用 reset_index() 展平为标准DataFrame。
import pandas as pd
# 创建分钟级时间序列
dates = pd.date_range("2023-01-01", periods=1000, freq="T")
ts = pd.Series(range(1000), index=dates)
# 重采样为每日均值
daily_mean = ts.resample("D").mean()
# 重采样为每周五的值(W-FRI)
weekly_fri = ts.resample("W-FRI").last()
⚠️ 注意:重采样后索引变为时间戳类型;缺失值需后续处理(如 .interpolate())。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# 子图1:折线图
axes[0, 0].plot(x, np.sin(x), "r--", label="sin(x)")
axes[0, 0].legend()
axes[0, 0].set_title("三角函数")
# 子图2:散点图
axes[0, 1].scatter(x[:50], np.cos(x[:50]), c="blue")
axes[0, 1].set_xlabel("x")
axes[0, 1].set_ylabel("cos(x)")
# 子图3:直方图
axes[1, 0].hist(np.random.randn(1000), bins=30, color="green", alpha=0.7)
axes[1, 0].set_title("正态分布")
# 子图4:饼图
sizes = [30, 40, 20, 10]
labels = ["A", "B", "C", "D"]
axes[1, 1].pie(sizes, labels=labels, autopct="%1.1f%%")
axes[1, 1].set_title("分布比例")
plt.tight_layout()
plt.show()
📌 技巧:使用 plt.tight_layout() 自动调整子图间距,避免标签重叠。
用Python解放双手,实现Excel处理、邮件发送、文件批量操作、系统任务调度等高频办公自动化场景。
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill
wb = Workbook()
ws = wb.active
ws.title = "销售汇总"
# 表头
headers = ["产品", "销量", "单价", "总额"]
ws.append(headers)
# 数据
data = [
["A产品", 120, 9.9, "=B2*C2"],
["B产品", 85, 15.0, "=B3*C3"],
["C产品", 200, 5.5, "=B4*C4"]
]
for row in data:
ws.append(row)
# 样式设置
for cell in ws[1]:
cell.font = Font(bold=True, color="FFFFFF")
cell.fill = PatternFill(start_color="037EF3", fill_type="solid")
cell.alignment = Alignment(horizontal="center")
# 自动调整列宽
for col in ws.columns:
max_len = max(len(str(cell.value)) for cell in col)
ws.column_dimensions[col[0].column_letter].width = max_len + 2
# 添加合计行
ws.append(["合计", f"=SUM(B2:B4)", f"=AVERAGE(C2:C4)", f"=SUM(D2:D4)"])
wb.save("sales_report.xlsx")
📌 扩展:可结合 openpyxl.utils.dataframe.dataframe_to_rows() 直接导入Pandas DataFrame。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# 配置信息
sender = "your_email@example.com"
password = "your_password"
receiver = "recipient@example.com"
# 构建邮件
msg = MIMEMultipart()
msg["From"] = sender
msg["To"] = receiver
msg["Subject"] = "自动化报表"
# HTML正文
html = """
销售日报
今日总销量:405件
详情见附件。
"""
msg.attach(MIMEText(html, "html", "utf-8"))
# 附件
with open("sales_report.xlsx", "rb") as f:
part = MIMEBase("application", "octet-stream")
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition",
'attachment; filename="sales_report.xlsx"')
msg.attach(part)
# 发送
with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
server.login(sender, password)
server.sendmail(sender, receiver, msg.as_string())
⚠️ 安全提示:密码应使用环境变量或配置文件存储,避免硬编码;企业邮箱需开启SMTP服务权限。
import schedule
import time
from datetime import datetime
def backup_database():
print(f"[{datetime.now()}] 开始数据库备份...")
# 实际备份逻辑(如调用mysqldump)
time.sleep(2)
print(f"[{datetime.now()}] 备份完成!")
# 每天2:30执行
schedule.every().day.at("02:30").do(backup_database)
# 每3小时执行一次
schedule.every(3).hours.do(backup_database)
# 启动调度循环
while True:
schedule.run_pending()
time.sleep(1)
📌 注意:此方案需保持脚本持续运行;生产环境建议结合systemd或Docker容器部署。
import pyautogui
import time
# 等待用户切换到目标窗口
time.sleep(3)
# 获取屏幕分辨率
width, height = pyautogui.size()
print(f"屏幕尺寸:{width}x{height}")
# 移动鼠标到屏幕中心并点击
pyautogui.click(width // 2, height // 2)
# 输入文本
pyautogui.write("Hello, Python Automation!", interval=0.1)
# 按回车
pyautogui.press("enter")
# 截图指定区域
screenshot = pyautogui.screenshot(region=(100, 100, 400, 300))
screenshot.save("region.png")
💡 应用场景:UI自动化测试、重复性操作替代、无障碍辅助工具开发。
基于requests+BeautifulSoup/selenium,构建稳定、合规的数据采集系统,注重反爬应对与数据清洗。
import requests
from bs4 import BeautifulSoup
import time
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
def scrape_news():
url = "https://example-news.com"
try:
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "lxml")
items = []
for article in soup.select(".news-item"):
title = article.select_one(".title").get_text(strip=True)
link = article.a["href"]
date = article.select_one(".date").get_text(strip=True)
items.append({"title": title, "link": link, "date": date})
return items
except Exception as e:
print(f"抓取失败:{e}")
return []
# 调用并打印结果
news_list = scrape_news()
for item in news_list[:3]:
print(f"{item['date']} - {item['title']}")
📌 反爬应对:合理设置User-Agent、添加Referer头;控制请求频率(time.sleep(1));使用代理池轮换IP。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("--headless") # 无头模式
options.add_argument("--no-sandbox")
driver = webdriver.Chrome(options=options)
try:
driver.get("https://example.com/dynamic")
# 等待元素加载完成
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, ".dynamic-content"))
)
content = driver.find_element(By.CSS_SELECTOR, ".dynamic-content").text
print(content)
finally:
driver.quit()
⚠️ 注意:selenium开销较大,仅用于JS渲染场景;优先考虑API逆向分析替代方案。
import re
html = """
邮箱:test@example.com
技术支持:support@domain.org
"""
# 邮箱正则(基础版)
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = re.findall(pattern, html)
print(emails) # → ['test@example.com', 'support@domain.org']
📌 进阶:更严格的邮箱验证可用RFC 5322标准正则,但通常基础版已满足需求;实际项目中建议结合DNS MX记录二次验证。
import sqlite3
# 创建数据库表
conn = sqlite3.connect("news.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
url TEXT UNIQUE,
publish_date TEXT
)
""")
# 插入数据(防重复)
articles = [
("标题1", "http://example.com/1", "2023-10-01"),
("标题2", "http://example.com/2", "2023-10-02")
]
cursor.executemany(
"INSERT OR IGNORE INTO articles (title, url, publish_date) VALUES (?, ?, ?)",
articles
)
conn.commit()
conn.close()
💡 优势:SQLite轻量无依赖,适合中小型项目;INSERT OR IGNORE避免重复插入。
涵盖Scikit-learn、TensorFlow等主流框架,提供从数据预处理到模型评估的完整流水线代码。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
# 加载数据
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练/测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 训练模型
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)
# 预测与评估
y_pred = clf.predict(X_test)
print(classification_report(y_test, y_pred, target_names=iris.target_names))
# 混淆矩阵
print(confusion_matrix(y_test, y_pred))
📌 关键点:stratify=y确保分层抽样;随机种子固定保证结果可复现;使用classification_report查看精确率/召回率/F1值。
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
# 示例数据
df = pd.DataFrame({
"age": [25, 30, None, 40],
"city": ["北京", "上海", "广州", "北京"],
"income": [5000, 8000, 6000, None]
})
# 定义列类型
numeric_features = ["age", "income"]
categorical_features = ["city"]
# 构建预处理管道
preprocessor = ColumnTransformer(
transformers=[
("num",
Pipeline(steps=[("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())]),
numeric_features),
("cat",
Pipeline(steps=[("imputer", SimpleImputer(strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore"))]),
categorical_features)
])
# 拟合并转换
X_processed = preprocessor.fit_transform(df)
print(X_processed.shape) # → (4, 6)
💡 实践建议:预处理步骤必须与模型训练同步进行,避免数据泄露;实际项目中使用Pipeline封装整个流程。
import joblib
# 保存模型
joblib.dump(clf, "iris_rf_model.pkl")
# 加载模型
loaded_model = joblib.load("iris_rf_model.pkl")
# 预测新样本
new_sample = [[5.1, 3.5, 1.4, 0.2]]
prediction = loaded_model.predict(new_sample)
print(iris.target_names[prediction[0]]) # → 'setosa'
📌 注意:确保模型与scikit-learn版本兼容;生产环境建议使用Docker容器化部署。
精选高频技术问题,提供深度解答与解决方案,助您避开常见陷阱。
print "Hi"),Python 3中是函数(print("Hi"))5/2=2,Python 3中5/2=2.5(//为整除)u前缀except Exception as e:,Python 2支持except Exception, e:📌 建议:新项目必须使用Python 3;旧项目迁移可借助2to3工具辅助转换。
GIL是CPython解释器的机制,确保同一时刻仅有一个线程执行Python字节码。其影响如下:
💡 解决方案:CPU密集型任务用multiprocessing;I/O密集型用threading或asyncio。
不同项目依赖不同版本的库,全局安装易导致冲突。虚拟环境提供独立空间:
# 创建虚拟环境
python -m venv myenv
# 激活(Windows)
myenv\Scripts\activate
# 激活(Linux/macOS)
source myenv/bin/activate
# 退出
deactivate
📌 最佳实践:每个项目独立环境;用requirements.txt管理依赖版本。
| 优化方向 | 推荐方案 | 预期提升 |
|---|---|---|
| 算法优化 | 选择更优算法(如用字典替代列表查找) | 数量级提升 |
| 数据结构 | 使用deque代替list做队列 |
显著提升 |
| C扩展 | NumPy/Cython/Numba | 10~100倍 |
| 多进程 | multiprocessing绕过GIL |
CPU核数倍 |
| 异步编程 | asyncio优化I/O等待 |
I/O密集型显著 |
⚠️ 警告:优先优化算法与数据结构;过早优化是万恶之源(Donald Knuth)。
📌 资源推荐:官方文档、Real Python、Python官方教程、《流畅的Python》
| 类别 | 工具名称 | 用途 |
|---|---|---|
| 编辑器 | VS Code + Python插件 | 智能提示/调试/格式化 |
| 包管理 | pip + Poetry | 依赖管理与虚拟环境 |
| 代码检查 | Flake8 / Pylint | 静态分析与规范检查 |
| 调试 | pdb / ipdb | 命令行调试 |
| 交互式 | Jupyter Notebook | 数据探索与演示 |
| 文档生成 | Sphinx | 自动生成API文档 |
新增asyncio异步编程实战案例;优化爬虫章节反爬策略说明;修复部分示例在Python 3.12下的兼容性问题。
更新Web开发章节,增加FastAPI 0.110+新特性;补充数据预处理中的特征缩放技巧。
新增自动化办公章节,覆盖Excel、邮件、GUI自动化;优化机器学习章节的特征工程流程图。
网站正式上线,首发包含基础语法、Web开发、数据分析三大模块共20+可运行实例。
快速导航至各核心模块: