软件研发 --- 一篇文章学python
Python 是一种高级、通用、解释型编程语言,由 Guido van Rossum(吉多·范罗苏姆) 于 1991年 首次发布。Python 被誉为 "胶水语言",几乎可以应用于任何领域,是当今最流行的编程语言之一!
Python 的名字来源于英国喜剧团体 Monty Python,而非蟒蛇。
优点
语法简单,易于学习
50万第三方包极其丰富
开源免费跨平台
社区强大
胶水语言,可轻松调用 C/C++/Java 等语言的模块
缺点
运行慢内存占用高
多线程无法真正利用多核 CPU
运行时报错难以发现
不支持移动端开发,操作系统、驱动、游戏引擎等
容易被反编译
不同py版本编写的代码可能不兼容
最擅长的领域:
AI(TensorFlow、PyTorch)
数据分析/科学计算(Pandas、NumPy、Jupyter、 SciPy、SymPy)
自动化脚本
网络爬虫(Scrapy、BeautifulSoup)
网络安全
量化金融 Zipline、Backtrader
一句话总结:Python 用开发速度换运行速度,是 AI 和数据领域的王者,但不适合追求极致性能和移动端的场景。
完整学习路径图
第一部分:基础篇(能写代码)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
环境搭建 → 变量/类型 → 数据结构 → 字符串处理 → 正则表达式
运算符/表达式 → 流程控制 → 函数 → 面向对象 → 标准库/自定义库
第二部分:高级篇(能写有用的代码)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
文件操作 → 网络操作 → 数据库操作
异常处理 → 并发编程 → 安全编程
第三部分:交付篇(能交付项目)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
工程化(调试/设计模式/Git/测试/项目结构)
部署运维(Docker/CI·CD/监控告警/定时任务)
最终:依据项目多练习代码!
核心原则:每个知识点都要写代码,看懂不等于会,项目实战才是最好的学习方式。
第一部分:基础篇
掌握编程的核心概念与基本能力
1. 环境搭建
# ==================== 安装Python ====================
# Windows: 下载安装包
# 访问 https://www.python.org/downloads/
# ⚠️ 安装时勾选 "Add Python to PATH"
# Mac:
brew install python3
# Linux(Ubuntu):
sudo apt update && sudo apt install python3 python3-pip
# 验证安装
python3 --version # Python 3.12.x
pip3 --version # pip 24.x
# ==================== 开发工具 ====================
# 方式一:VS Code(推荐初学者)
# 下载 https://code.visualstudio.com/
# 安装 Python 扩展插件
# 方式二:PyCharm(专业IDE)
# 下载 https://www.jetbrains.com/pycharm/
# 方式三:命令行直接运行
python3 hello.py
# ==================== 虚拟环境(项目隔离) ====================
# 创建虚拟环境
python3 -m venv myproject_env
# 激活
# Windows:
myproject_env\Scripts\activate
# Mac/Linux:
source myproject_env/bin/activate
# 安装依赖
pip install requests pandas
# 导出/安装依赖清单
pip freeze > requirements.txt
pip install -r requirements.txt
# 退出虚拟环境
deactivate
# hello.py —— 第一个程序
print("Hello, Python!")
# 运行:python3 hello.py
# 输出:Hello, Python!
一、编码
- Python 3 源码文件默认使用 UTF-8 编码,字符串均为 Unicode。
- 可通过
# -*- coding: cp-1252 -*-指定其他编码。
二、标识符
- 首字符:字母(a-z, A-Z)或下划线
_ - 其余部分:字母、数字、下划线
- 大小写敏感:
count和Count是不同的标识符 - 不能使用保留关键字(如
if、for、class) - Python 3 支持 Unicode 标识符(如中文变量名
姓名 = "张三")
age = 25 # 普通变量名,最常见
user_name = "Alice" # 用下划线连接单词,清晰易读
_total = 100 # 下划线开头通常表示“内部使用”或“私有”
MAX_SIZE = 1024 # 全大写通常表示“常量”(固定不变的值)
calculate_area() # 函数名,动词+名词
StudentInfo # 类名,首字母大写(驼峰命名法)
__private_var # 双下划线开头,有特殊含义
三、保留关键字(35个)
通过 import keyword; keyword.kwlist 查看,涵盖:
| 类别 | 关键字 |
|---|---|
| 逻辑值 | True, False, None |
| 逻辑运算 | 和 , 或 , 非 |
| 条件控制 | if, elif, else |
| 循环控制 | for, while, break, continue |
| 异常处理 | try, except, finally, raise |
| 函数 | def, return, lambda |
| 类与对象 | class, del |
| 模块导入 | import, from, as |
| 作用域 | global, nonlocal |
| 异步 | async, await |
| 其他 | assert, in, is, pass, with, yield |
四、注释
- 单行注释:
# 注释内容 - 多行注释:使用
'''...'''或"""..."""
五、行与缩进
- Python 使用缩进表示代码块(而非
{}) - 同一代码块的缩进空格数必须一致,否则报
IndentationError
六、多行语句
- 使用反斜杠
\换行:Pythontotal = a + \ b + \ c - 在
[]、{}、()中可直接换行,无需\
七、基本数据类型
| 类型 | 说明 | 示例 |
|---|---|---|
int |
整数 | 1, -5 |
bool |
布尔 | True, False |
float |
浮点数 | 1.23, 3E-2 |
complex |
复数 | 1 + 2j |
八、字符串
- 单引号
'和双引号"等价 - 三引号
'''/"""用于多行字符串 r"..."原始字符串(不转义)+连接,*重复- 索引:从左
0开始,从右-1开始 - 切片:
str[start:end:step](start 包含,end 不包含) - 字符串不可变
九、其他语法要点
- 空行:用于分隔代码段,非语法要求但属于良好习惯
- 用户输入:
input("提示信息") - 同行多语句:用分号
;分隔(不推荐) - 代码组:缩进相同的语句构成代码块,复合语句首行以
:结束 - print 不换行:
print(x, end="")
十、模块导入
import somemodule # 导入整个模块
from somemodule import func # 导入特定函数
from somemodule import func1, func2 # 导入多个函数
from somemodule import * # 导入全部(不推荐)
十一、命令行参数
python -h查看帮助信息- 通过
sys.argv获取命令行参数
2. 变量、常量与数据类型
如何定义基本数据
# ==================== 变量 ====================
# 变量 = 给数据起名字,方便后续使用
# Python是动态类型语言,不需要声明类型
name = "张三" # 字符串 str
age = 25 # 整数 int
salary = 8500.50 # 浮点数 float
is_active = True # 布尔值 bool(True/False)
nothing = None # 空值 NoneType
# 查看类型
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
# 动态类型:同一个变量可以改变类型(但不推荐)
x = 10
x = "hello" # 合法,但会让代码难以维护
# ==================== 常量 ====================
# Python没有真正的常量语法,约定用全大写表示"不应修改"
MAX_RETRY = 3
PI = 3.14159
DB_HOST = "192.168.1.100"
# ==================== 类型转换 ====================
# 字符串 → 数字
num = int("123") # 123
price = float("99.9") # 99.9
# 数字 → 字符串
text = str(100) # "100"
# 数字 → 布尔
print(bool(0)) # False(0为假)
print(bool(42)) # True(非0为真)
print(bool("")) # False(空字符串为假)
print(bool("hello")) # True(非空为真)
# ==================== 多重赋值 ====================
a, b, c = 1, 2, 3
x = y = z = 0 # 三个变量都等于0
# ==================== 命名规则 ====================
# ✅ 合法:字母/下划线开头,包含字母/数字/下划线
user_name = "张三"
_private = "内部变量"
count2 = 10
# ❌ 非法
# 2name = "xx" # 不能以数字开头
# my-name = "xx" # 不能用连字符
# class = "xx" # 不能用保留关键字
3. 数据结构
更复杂的数据如何构成
# ==================== 列表 list ====================
# 有序、可变、允许重复
fruits = ["苹果", "香蕉", "橘子", "香蕉"]
# 增
fruits.append("葡萄") # 末尾添加
fruits.insert(1, "西瓜") # 指定位置插入
# 删
fruits.remove("香蕉") # 删除第一个匹配项
last = fruits.pop() # 弹出最后一个
del fruits[0] # 按索引删除
# 改
fruits[0] = "芒果"
# 查
print(fruits[0]) # 索引访问
print(len(fruits)) # 长度
print("芒果" in fruits) # 成员判断
# 切片
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # [1, 2, 3]
print(nums[::2]) # [0, 2, 4] 步长2
print(nums[::-1]) # [5, 4, 3, 2, 1, 0] 反转
# 列表推导式
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# 排序
nums = [3, 1, 4, 1, 5]
nums.sort() # 原地排序 [1, 1, 3, 4, 5]
sorted_nums = sorted(nums, reverse=True) # 返回新列表,不改原列表
# ==================== 元组 tuple ====================
# 有序、不可变(创建后不能修改)
point = (10, 20)
single = (42,) # 单元素元组必须加逗号!
x, y = point # 拆包
print(point[0]) # 10
# point[0] = 99 # ❌ 报错!元组不可变
# 用途:函数返回多个值、作为字典的key、保护数据不被修改
# ==================== 字典 dict ====================
# 键值对、键唯一、3.7+保持插入顺序
student = {
"name": "张三",
"age": 20,
"scores": [85, 90, 78]
}
# 增/改
student["gender"] = "男" # 新增
student["age"] = 21 # 修改
# 查
print(student["name"]) # 张三(键不存在会报错)
print(student.get("phone", "无")) # 安全获取,不存在返回默认值
# 删
del student["gender"]
student.pop("age")
# 遍历
for key, value in student.items():
print(f"{key}: {value}")
# 字典推导式
word = "hello"
char_count = {c: word.count(c) for c in set(word)}
# {'h': 1, 'e': 1, 'l': 2, 'o': 1}
# ==================== 集合 set ====================
# 无序、不重复、支持数学集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a.add(5) # 添加元素
a.discard(1) # 删除(不存在不报错)
print(a & b) # 交集 {3, 4, 5}
print(a | b) # 并集 {2, 3, 4, 5, 6}
print(a - b) # 差集 {2}
# 去重
names = ["张三", "李四", "张三", "王五"]
unique_names = list(set(names)) # ['张三', '李四', '王五']
# ==================== 总结对比 ====================
"""
类型 有序 可变 重复 用途
list ✅ ✅ ✅ 通用序列,最常用
tuple ✅ ❌ ✅ 不可变数据,函数返回值
dict ✅* ✅ 键不可 键值映射,最常用之一
set ❌ ✅ ❌ 去重、集合运算
"""
4. 字符串处理
# ==================== 字符串定义 ====================
s1 = 'hello'
s2 = "it's OK"
s3 = """多行
字符串"""
s4 = r"C:\Users\test" # 原始字符串(不转义)
# ==================== 索引与切片 ====================
text = "Python编程"
# 索引 P y t h o n 编 程
# 0 1 2 3 4 5 6 7
# -8 -7 -6 -5 -4 -3 -2 -1
print(text[0]) # P
print(text[-1]) # 程
print(text[0:6]) # Python
print(text[::-1]) # 程编nohtyP(反转)
# ==================== 常用方法 ====================
msg = " Hello World "
# 去除空白
print(msg.strip()) # "Hello World"
print(msg.lstrip()) # "Hello World "
# 大小写
print("hello".upper()) # HELLO
print("HELLO".lower()) # hello
print("hello world".title()) # Hello World
print("hello world".capitalize()) # Hello world
# 查找与替换
print("hello world".find("world")) # 6(找不到返回-1)
print("hello world".index("world")) # 6(找不到报错)
print("hello world".replace("world", "python")) # hello python
print("hello world".count("l")) # 3
# 判断
print("123".isdigit()) # True 是否全是数字
print("abc".isalpha()) # True 是否全是字母
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
# 分割与连接
print("a,b,c".split(",")) # ['a', 'b', 'c']
print(",".join(["a", "b", "c"])) # "a,b,c"
# 格式化(三种方式)
name, age = "张三", 25
print("姓名:%s,年龄:%d" % (name, age)) # ① %格式化
print("姓名:{},年龄:{}".format(name, age)) # ② format方法
print(f"姓名:{name},年龄:{age}") # ③ f-string(推荐✅)
print(f"计算:{3 + 5}") # f-string支持表达式
print(f"价格:{99.5:.2f}") # 保留2位小数:99.50
5. 正则表达式
字符串匹配自定义的模式
import re
text = "联系人:张三 138-0001-2345,李四 lisi@mail.com,日期 2025-01-15"
# ==================== 常用语法速查 ====================
"""
. 匹配任意字符(除换行)
\d 数字 [0-9]
\w 字母/数字/下划线
\s 空白字符(空格/制表符/换行)
* 前面的字符出现 0次或多次
+ 前面的字符出现 1次或多次
? 前面的字符出现 0次或1次
{n,m} 前面的字符出现 n到m次
[] 字符集合,如 [a-z] [0-9]
^ 开头
$ 结尾
() 分组捕获
| 或
"""
# ==================== findall: 查找所有匹配 ====================
phones = re.findall(r"1[3-9]\d-\d{4}-\d{4}", text)
print(phones) # ['138-0001-2345']
emails = re.findall(r"\w+@\w+\.\w+", text)
print(emails) # ['lisi@mail.com']
dates = re.findall(r"\d{4}-\d{2}-\d{2}", text)
print(dates) # ['2025-01-15']
chinese = re.findall(r"[\u4e00-\u9fa5]+", text)
print(chinese) # ['联系人', '张三', '李四', '日期']
# ==================== search: 找第一个匹配 ====================
match = re.search(r"(\d{3})-(\d{4})-(\d{4})", text)
if match:
print(match.group()) # 138-0001-2345(完整匹配)
print(match.group(1)) # 138(第1个分组)
print(match.group(2)) # 0001(第2个分组)
# ==================== sub: 替换 ====================
cleaned = re.sub(r"\d{3}-\d{4}-\d{4}", "***", text)
print(cleaned) # 联系人:张三 ***,李四 lisi@mail.com,日期 2025-01-15
# ==================== match: 从开头匹配 ====================
result = re.match(r"联系人", text)
print(result.group()) # 联系人
# ==================== 贪婪 vs 非贪婪 ====================
html = "<div>hello</div><div>world</div>"
print(re.findall(r"<div>.*</div>", html)) # 贪婪:匹配最长
# ['<div>hello</div><div>world</div>']
print(re.findall(r"<div>.*?</div>", html)) # 非贪婪:匹配最短
# ['<div>hello</div>', '<div>world</div>']
# ==================== compile: 预编译(提升性能) ====================
phone_pattern = re.compile(r"1[3-9]\d{9}")
result = phone_pattern.findall("手机号13800001234和13900005678")
print(result) # ['13800001234', '13900005678']
6. 运算符与表达式
数据如何处理
# ==================== 算术运算符 ====================
print(17 + 3) # 20 加
print(17 - 3) # 14 减
print(17 * 3) # 51 乘
print(17 / 3) # 5.666 除(返回浮点数)
print(17 // 3) # 5 整除(取商)
print(17 % 3) # 2 取余(取余数)
print(2 ** 10) # 1024 幂
# ==================== 赋值运算符 ====================
x = 10
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x //= 5 # x = x // 5 → 4
x **= 3 # x = x ** 3 → 64
# ==================== 比较运算符 ====================
print(10 > 5) # True
print(10 == 10) # True
print(10 != 5) # True
print(10 >= 10) # True
# 返回值都是布尔值 True / False
# ==================== 逻辑运算符 ====================
age = 25
salary = 10000
print(age > 18 and salary > 5000) # True 两个都为真→真
print(age > 30 or salary > 5000) # True 一个为真→真
print(not age > 30) # True 取反
# ==================== 成员运算符 ====================
fruits = ["苹果", "香蕉", "橘子"]
print("苹果" in fruits) # True 是否在集合中
print("葡萄" not in fruits) # True 是否不在集合中
# ==================== 身份运算符 ====================
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True 值相等
print(a is b) # False 不是同一个对象
print(a is c) # True 是同一个对象(c指向a)
# ==================== 三元表达式 ====================
score = 85
level = "及格" if score >= 60 else "不及格"
print(level) # 及格
7. 流程控制
代码如何执行(代码的结构)
# ==================== 条件判断 ====================
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好") # ← 执行这个
elif score >= 60:
print("及格")
else:
print("不及格")
# 简写:三元表达式
result = "通过" if score >= 60 else "未通过"
# ==================== for 循环 ====================
# 遍历列表
fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(fruit)
# 带索引遍历
for i, fruit in enumerate(fruits):
print(f"第{i+1}个: {fruit}")
# range() 生成数字序列
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 10, 2): # 1,3,5,7,9(步长2)
print(i)
# 遍历字典
person = {"name": "张三", "age": 25}
for key, value in person.items():
print(f"{key}: {value}")
# ==================== while 循环 ====================
count = 0
while count < 5:
print(count)
count += 1 # 别忘了更新条件,否则死循环!
# 实用示例:用户输入验证
while True:
pwd = input("请输入密码(至少6位): ")
if len(pwd) >= 6:
print("密码设置成功")
break # 跳出循环
print("密码太短,请重新输入")
# ==================== break / continue / else ====================
# break: 立即跳出循环
for i in range(10):
if i == 5:
break # 到5就停止
print(i) # 0 1 2 3 4
# continue: 跳过本次,进入下一次
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i) # 1 3 5 7 9
# for...else: 循环正常结束(没有break)时执行else
for i in range(5):
if i == 10: # 条件不会成立
break
else:
print("循环正常结束") # ← 会执行
# ==================== 嵌套循环 ====================
# 九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print() # 换行
8. 系统函数与自定义函数
重复代码块如何复用
# ==================== 常用系统内建函数 ====================
# 类型相关
print(type(42)) # <class 'int'>
print(isinstance(42, int)) # True
print(len("hello")) # 5
print(id(42)) # 内存地址
# 数学相关
print(abs(-10)) # 10
print(max(3, 7, 1, 9)) # 9
print(min(3, 7, 1, 9)) # 1
print(sum([1, 2, 3, 4])) # 10
print(round(3.14159, 2)) # 3.14
print(pow(2, 10)) # 1024
# 序列相关
print(range(5)) # range(0, 5) → 配合list()使用
print(list(range(5))) # [0, 1, 2, 3, 4]
print(sorted([3, 1, 4])) # [1, 3, 4]
print(reversed([1, 2, 3])) # 迭代器 → list() 转换
print(list(zip([1,2], ["a","b"]))) # [(1,'a'), (2,'b')]
# 输入输出
name = input("请输入姓名: ") # 从键盘读取(返回字符串)
print(f"你好, {name}")
# 进制转换
print(bin(10)) # 0b1010
print(oct(10)) # 0o12
print(hex(255)) # 0xff
# ==================== 自定义函数 ====================
def greet(name):
"""打招呼(这是文档字符串)"""
return f"你好, {name}!"
print(greet("张三")) # 你好, 张三!
# ==================== 参数类型 ====================
def create_user(name, age=18, *hobbies, **extra):
"""
name: 位置参数(必填)
age: 默认参数(可选,有默认值)
*hobbies: 可变参数(收集多余的位置参数→元组)
**extra: 关键字参数(收集多余的键值对→字典)
"""
print(f"姓名: {name}, 年龄: {age}")
print(f"爱好: {hobbies}")
print(f"其他: {extra}")
create_user("李明", 25, "篮球", "音乐", city="北京")
# 姓名: 李明, 年龄: 25
# 爱好: ('篮球', '音乐')
# 其他: {'city': '北京'}
# ==================== 返回多个值 ====================
def calc(a, b):
return a + b, a - b, a * b # 实际返回一个元组
add, sub, mul = calc(10, 3) # 拆包接收
print(add, sub, mul) # 13 7 30
# ==================== lambda 匿名函数 ====================
square = lambda x: x ** 2
print(square(5)) # 25
# 常用于排序
students = [("张三", 85), ("李四", 92), ("王五", 78)]
students.sort(key=lambda s: s[1], reverse=True)
print(students) # [('李四', 92), ('张三', 85), ('王五', 78)]
# ==================== 高阶函数 ====================
nums = [1, 2, 3, 4, 5]
# map: 对每个元素应用函数
doubled = list(map(lambda x: x * 2, nums)) # [2,4,6,8,10]
# filter: 过滤
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
# reduce: 累积
from functools import reduce
total = reduce(lambda a, b: a + b, nums) # 15
# ==================== 装饰器(函数增强) ====================
import time
def timer(func):
"""计时装饰器:测量函数执行时间"""
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f"{func.__name__} 耗时: {elapsed:.4f}秒")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "完成"
slow_function() # slow_function 耗时: 1.0012秒
9. 面向对象
多个相关函数如何一块复用
# ==================== 类的定义 ====================
class Student:
"""学生类"""
school = "Python学院" # 类属性(所有实例共享)
def __init__(self, name, age): # 构造方法
self.name = name # 实例属性
self.age = age
self._scores = [] # 约定私有属性(前缀_)
def add_score(self, score): # 实例方法
if 0 <= score <= 100:
self._scores.append(score)
else:
raise ValueError("成绩必须在0-100之间")
def get_average(self):
if not self._scores:
return 0
return sum(self._scores) / len(self._scores)
def __str__(self): # 打印对象时调用
return f"学生({self.name}, {self.age}岁)"
def __len__(self): # len()时调用
return len(self._scores)
# 使用
s = Student("张三", 20)
s.add_score(85)
s.add_score(92)
print(s) # 学生(张三, 20岁)
print(s.get_average()) # 88.5
print(len(s)) # 2
print(Student.school) # Python学院
# ==================== 继承 ====================
class GradStudent(Student):
"""研究生,继承自Student"""
def __init__(self, name, age, research):
super().__init__(name, age) # 调用父类构造
self.research = research
def __str__(self): # 方法重写(多态)
return f"研究生({self.name}, 方向: {self.research})"
g = GradStudent("李四", 24, "人工智能")
g.add_score(95) # 继承了父类方法
print(g) # 研究生(李四, 方向: 人工智能)
print(isinstance(g, Student)) # True
# ==================== 类方法与静态方法 ====================
class MathHelper:
@staticmethod # 静态方法:不需要实例
def is_even(n):
return n % 2 == 0
@classmethod # 类方法:操作类本身
def description(cls):
return f"这是 {cls.__name__} 工具类"
print(MathHelper.is_even(4)) # True
print(MathHelper.description()) # 这是 MathHelper 工具类
# ==================== @property 属性装饰器 ====================
class Circle:
def __init__(self, radius):
self._radius = radius
@property # 像属性一样访问
def area(self):
return 3.14159 * self._radius ** 2
@property
def radius(self):
return self._radius
@radius.setter # 设置时自动校验
def radius(self, value):
if value <= 0:
raise ValueError("半径必须大于0")
self._radius = value
c = Circle(5)
print(c.area) # 78.53975(不需要加括号)
c.radius = 10 # 通过setter修改
# c.radius = -1 # ❌ ValueError
10. 标准库与自定义库
多个相关对象如何一块复用
# ==================== 导入方式 ====================
import os # 导入整个模块
from datetime import datetime # 导入特定内容
from collections import Counter # 导入特定类
import json as j # 别名
# ==================== 常用标准库示例 ====================
# --- math: 数学 ---
import math
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4 向上取整
print(math.floor(3.8)) # 3 向下取整
print(math.pi) # 3.141592653589793
# --- datetime: 日期时间 ---
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-01-15 14:30:00
yesterday = now - timedelta(days=1)
date = datetime.strptime("2025-01-15", "%Y-%m-%d")
# --- json: 序列化 ---
import json
data = {"name": "张三", "age": 25}
json_str = json.dumps(data, ensure_ascii=False) # → JSON字符串
obj = json.loads(json_str) # → Python对象
# --- collections: 增强容器 ---
from collections import Counter, defaultdict, OrderedDict
words = ["apple", "banana", "apple", "cherry", "apple"]
print(Counter(words)) # Counter({'apple': 3, 'banana': 1, 'cherry': 1})
print(Counter(words).most_common(2)) # [('apple', 3), ('banana', 1)]
# --- random: 随机 ---
import random
print(random.randint(1, 100)) # 随机整数
print(random.choice(["a", "b", "c"])) # 随机选一个
random.shuffle([1, 2, 3, 4, 5]) # 打乱列表
# --- hashlib: 哈希 ---
import hashlib
md5 = hashlib.md5("hello".encode()).hexdigest()
print(md5) # 5d41402abc4b2a76b9719d911017c592
# ==================== 自定义模块 ====================
# --- utils/string_helper.py ---
"""字符串工具模块"""
def clean_text(text):
"""去除多余空白"""
return " ".join(text.split())
def mask_phone(phone):
"""手机号脱敏"""
return phone[:3] + "****" + phone[7:]
# --- utils/__init__.py ---
from .string_helper import clean_text, mask_phone
# --- main.py(使用自定义模块) ---
from utils import clean_text, mask_phone
print(clean_text(" hello world ")) # "hello world"
print(mask_phone("13800001234")) # "138****1234"
# ==================== 自定义包结构 ====================
"""
my_project/
├── main.py
├── utils/ # 工具包
│ ├── __init__.py # 包标识文件
│ ├── string_helper.py
│ └── date_helper.py
├── models/ # 数据模型包
│ ├── __init__.py
│ └── user.py
└── config/
├── __init__.py
└── settings.py
"""
第二部分:高级篇
从「能写代码」到「能写有用的代码」
11. 文件操作
对操作系统操作的支持
import os
import shutil
# ==================== 读写文本文件 ====================
# 写文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.write("第二行\n")
# 追加写入
with open("output.txt", "a", encoding="utf-8") as f:
f.write("追加的内容\n")
# 读取全部
with open("output.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取(推荐,节省内存)
with open("output.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 读取为列表
with open("output.txt", "r", encoding="utf-8") as f:
lines = f.readlines() # ['第一行\n', '第二行\n', ...]
# ==================== 读写二进制文件 ====================
# 复制图片
with open("photo.jpg", "rb") as src:
data = src.read()
with open("photo_copy.jpg", "wb") as dst:
dst.write(data)
# ==================== 目录操作 ====================
print(os.getcwd()) # 当前目录
print(os.path.exists("output.txt")) # 文件是否存在
print(os.path.isfile("output.txt")) # 是否是文件
print(os.path.isdir("data")) # 是否是目录
print(os.path.getsize("output.txt")) # 文件大小(字节)
os.makedirs("data/reports/2025", exist_ok=True) # 递归创建目录
# 列出目录内容
for name in os.listdir("./data"):
full_path = os.path.join("./data", name)
print(f"{name} - {'目录' if os.path.isdir(full_path) else '文件'}")
# 路径拼接(跨平台安全)
path = os.path.join("data", "reports", "report.txt")
# 获取文件名和扩展名
print(os.path.basename("/data/report.txt")) # report.txt
print(os.path.splitext("report.txt")) # ('report', '.txt')
# ==================== 文件复制/移动/删除 ====================
shutil.copy("output.txt", "backup.txt") # 复制
shutil.move("backup.txt", "data/") # 移动
os.remove("output.txt") # 删除文件
shutil.rmtree("data/old") # 删除目录(含内容)
# ==================== 命令执行 ====================
import subprocess
# 执行系统命令
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
# Windows:
# result = subprocess.run(["dir"], shell=True, capture_output=True, text=True)
# 检查命令是否成功
if result.returncode == 0:
print("命令执行成功")
12. 网络操作
import requests
import socket
import json
# ==================== HTTP请求(requests库) ====================
# GET请求
response = requests.get(
"https://api.example.com/users",
params={"page": 1, "size": 10},
headers={"Authorization": "Bearer token123"},
timeout=10
)
print(response.status_code) # 200
print(response.json()) # 解析JSON响应
# POST请求
data = {"username": "admin", "password": "123456"}
response = requests.post(
"https://api.example.com/login",
json=data,
timeout=10
)
result = response.json()
# 下载文件
resp = requests.get("https://example.com/file.pdf", stream=True)
with open("downloaded.pdf", "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
# Session保持(自动管理Cookie)
session = requests.Session()
session.post("https://example.com/login", data={"user": "admin", "pwd": "123"})
response = session.get("https://example.com/dashboard") # 自动带cookie
# ==================== Socket基础 ====================
# 简单TCP客户端
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("example.com", 80))
sock.send(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
data = sock.recv(4096)
print(data.decode())
sock.close()
# 检测端口是否开放
def check_port(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect((host, port))
s.close()
return True
except (socket.timeout, ConnectionRefusedError):
return False
print(check_port("baidu.com", 80)) # True
print(check_port("baidu.com", 8888)) # False
13. 数据库操作
对第三方系统操作的支持
# ==================== MySQL操作(PyMySQL) ====================
import pymysql
conn = pymysql.connect(
host="localhost", port=3306,
user="root", password="123456",
database="testdb", charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)
try:
with conn.cursor() as cursor:
# 查询
cursor.execute("SELECT * FROM users WHERE age >= %s", (18,))
users = cursor.fetchall()
for user in users:
print(f"{user['name']} - {user['age']}岁")
# 插入
cursor.execute(
"INSERT INTO users (name, age) VALUES (%s, %s)",
("张三", 25)
)
conn.commit()
print(f"新增ID: {cursor.lastrowid}")
# 批量插入
data = [("李四", 22), ("王五", 28)]
cursor.executemany(
"INSERT INTO users (name, age) VALUES (%s, %s)", data
)
conn.commit()
# 更新
cursor.execute("UPDATE users SET age=%s WHERE name=%s", (26, "张三"))
conn.commit()
# 删除
cursor.execute("DELETE FROM users WHERE name=%s", ("王五",))
conn.commit()
except Exception as e:
conn.rollback()
print(f"操作失败: {e}")
finally:
conn.close()
# ==================== Redis操作 ====================
import redis
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
# 字符串
r.set("name", "张三", ex=3600) # 设置,过期时间3600秒
print(r.get("name")) # 张三
# 哈希
r.hset("user:1", mapping={"name": "张三", "age": "25"})
print(r.hgetall("user:1")) # {'name': '张三', 'age': '25'}
# 列表(队列)
r.rpush("task_queue", "task1", "task2")
task = r.lpop("task_queue") # 取出 task1
# 设置过期
r.expire("name", 60) # 60秒后过期
# ==================== SQLite(轻量级/无需服务器) ====================
import sqlite3
conn = sqlite3.connect("local.db") # 文件数据库
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute("INSERT INTO notes (title, content) VALUES (?, ?)",
("学习笔记", "今天学了Python"))
conn.commit()
cursor.execute("SELECT * FROM notes")
for row in cursor.fetchall():
print(row)
conn.close()
14. 异常处理
运行报错如何处理
# ==================== 基本捕获 ====================
try:
num = int(input("输入数字: "))
result = 100 / num
except ValueError:
print("输入的不是数字")
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"未知错误: {type(e).__name__}: {e}")
else:
print(f"结果: {result}") # 无异常时执行
finally:
print("执行完毕") # 无论如何都执行
# ==================== 常见异常类型 ====================
"""
ValueError 值不对 int("abc")
TypeError 类型不对 "hello" + 123
KeyError 键不存在 dict["不存在的key"]
IndexError 索引越界 list[999]
FileNotFoundError 文件不存在 open("不存在.txt")
AttributeError 属性不存在 "hello".不存在的方法()
ZeroDivisionError 除以零 1 / 0
ImportError 导入失败 import 不存在的模块
ConnectionError 连接失败 请求不可达的服务器
TimeoutError 超时 网络请求超时
"""
# ==================== 手动抛出异常 ====================
def set_age(age):
if not isinstance(age, int):
raise TypeError("年龄必须是整数")
if age < 0 or age > 150:
raise ValueError(f"年龄不合法: {age}")
return age
# ==================== 自定义异常 ====================
class BusinessError(Exception):
"""业务异常基类"""
def __init__(self, code, message):
self.code = code
self.message = message
super().__init__(self.message)
class InsufficientBalance(BusinessError):
"""余额不足"""
def __init__(self, balance, amount):
super().__init__(4001, f"余额不足: 余额{balance}, 需要{amount}")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalance(balance, amount)
return balance - amount
try:
withdraw(100, 200)
except BusinessError as e:
print(f"[{e.code}] {e.message}")
# [4001] 余额不足: 余额100, 需要200
# ==================== 异常传递 ====================
def func_a():
return 1 / 0 # 异常发生
def func_b():
func_a() # 异常向上传递
def func_c():
try:
func_b() # 在这里统一捕获
except ZeroDivisionError:
print("在func_c中捕获了异常")
func_c() # 输出: 在func_c中捕获了异常
# ==================== 实用模式:重试机制 ====================
import time
def retry(func, max_retries=3, delay=1):
"""带重试的函数执行"""
for attempt in range(1, max_retries + 1):
try:
return func()
except Exception as e:
print(f"第{attempt}次失败: {e}")
if attempt == max_retries:
raise
time.sleep(delay)
# 使用
# retry(lambda: requests.get("https://unstable-api.com", timeout=5))
15. 并发编程
如何多个任务一起做,提高效率
# ==================== 多线程(适合I/O密集型) ====================
import threading
import time
def download(url, name):
"""模拟下载任务"""
print(f"[{name}] 开始下载 {url}")
time.sleep(2) # 模拟耗时
print(f"[{name}] 下载完成")
# 串行执行:6秒
# download("url1", "任务1")
# download("url2", "任务2")
# download("url3", "任务3")
# 多线程并行:约2秒
threads = []
for i in range(3):
t = threading.Thread(target=download, args=(f"url{i}", f"任务{i}"))
threads.append(t)
t.start()
for t in threads:
t.join() # 等待所有线程完成
print("全部下载完成")
# ==================== 线程池(推荐) ====================
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_data(url):
"""模拟获取数据"""
time.sleep(1)
return f"{url} 的数据"
urls = [f"https://api.example.com/page/{i}" for i in range(10)]
with ThreadPoolExecutor(max_workers=5) as executor:
# 提交所有任务
futures = {executor.submit(fetch_data, url): url for url in urls}
# 获取结果(谁先完成先处理谁)
for future in as_completed(futures):
url = futures[future]
result = future.result()
print(f"{url} → {result}")
# ==================== 多进程(适合CPU密集型) ====================
from concurrent.futures import ProcessPoolExecutor
def heavy_compute(n):
"""CPU密集型计算"""
return sum(i * i for i in range(n))
with ProcessPoolExecutor(max_workers=4) as executor:
results = executor.map(heavy_compute, [10**6, 10**6, 10**6, 10**6])
for r in results:
print(r)
# ==================== 异步编程 asyncio ====================
import asyncio
async def fetch(name, delay):
"""异步任务"""
print(f"[{name}] 开始")
await asyncio.sleep(delay) # 异步等待(不阻塞)
print(f"[{name}] 完成")
return f"{name}的结果"
async def main():
# 并发执行3个任务
tasks = [
fetch("任务A", 2),
fetch("任务B", 1),
fetch("任务C", 3),
]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
# 总耗时约3秒(取最长的那个),而非 2+1+3=6秒
# ==================== 线程锁(解决数据竞争) ====================
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with lock: # 加锁保护共享数据
counter += 1
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)
t1.start(); t2.start()
t1.join(); t2.join()
print(counter) # 200000(不加锁可能小于这个值)
16. 安全编程
让系统更安全
import hashlib
import hmac
import secrets
import html
# ==================== 密码哈希(不要存明文密码!) ====================
def hash_password(password, salt=None):
"""安全的密码哈希"""
if salt is None:
salt = secrets.token_hex(16)
hashed = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 100000)
return salt + ":" + hashed.hex()
def verify_password(password, stored):
"""验证密码"""
salt = stored.split(":")[0]
return hash_password(password, salt) == stored
stored_pwd = hash_password("mypassword123")
print(verify_password("mypassword123", stored_pwd)) # True
print(verify_password("wrongpassword", stored_pwd)) # False
# ==================== 安全随机数 ====================
token = secrets.token_hex(32) # 安全随机Token
url_token = secrets.token_urlsafe(32) # URL安全的Token
print(token)
# ==================== 防SQL注入 ====================
# ❌ 危险:字符串拼接
# sql = f"SELECT * FROM users WHERE name = '{user_input}'"
# ✅ 安全:参数化查询
# cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
# ==================== 防XSS攻击 ====================
user_input = '<script>alert("hacked")</script>'
safe_text = html.escape(user_input)
print(safe_text)
# <script>alert("hacked")</script>
# ==================== 输入验证 ====================
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
def validate_phone(phone):
pattern = r'^1[3-9]\d{9}$'
return bool(re.match(pattern, phone))
print(validate_email("test@example.com")) # True
print(validate_email("invalid-email")) # False
print(validate_phone("13800001234")) # True
# ==================== 敏感信息脱敏 ====================
def mask_phone(phone):
return phone[:3] + "****" + phone[7:]
def mask_id_card(id_card):
return id_card[:6] + "********" + id_card[14:]
print(mask_phone("13800001234")) # 138****1234
print(mask_id_card("110101199001011234")) # 110101********1234
# ==================== 环境变量管理敏感配置 ====================
import os
# 不要在代码中硬编码密码!
# ❌ db_password = "123456"
# ✅ 使用环境变量
db_password = os.environ.get("DB_PASSWORD", "default_for_dev")
# 或使用 .env 文件
# pip install python-dotenv
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("API_KEY")
第三部分:交付篇
从「能写代码」到「能交付项目」
17. 工程化
调试技巧
# ==================== print调试(最基础) ====================
def calc_total(items):
total = 0
for item in items:
print(f"[DEBUG] 处理: {item}, 当前total={total}") # 调试输出
total += item["price"] * item["qty"]
return total
# ==================== logging(推荐替代print) ====================
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("app.log", encoding="utf-8"),
logging.StreamHandler() # 同时输出到控制台
]
)
logger = logging.getLogger(__name__)
logger.debug("调试信息") # 开发时查看
logger.info("正常流程") # 关键操作记录
logger.warning("警告信息") # 需要注意
logger.error("错误信息") # 出错了
logger.critical("严重错误") # 系统级别错误
# ==================== 断点调试 ====================
# 方式一:pdb(命令行调试)
# import pdb; pdb.set_trace() # 代码中插入断点
# 方式二:breakpoint()(Python 3.7+)
# breakpoint() # 更简洁
# 方式三:IDE调试(推荐)
# VS Code / PyCharm 中点击行号设置断点,F5启动调试
# F10 单步跳过 | F11 单步进入 | Shift+F11 跳出
设计模式
# ==================== 单例模式 ====================
class Database:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if not hasattr(self, 'initialized'):
self.connection = "数据库连接"
self.initialized = True
db1 = Database()
db2 = Database()
print(db1 is db2) # True(同一个实例)
# ==================== 工厂模式 ====================
class ReportFactory:
"""根据类型创建不同的报告生成器"""
@staticmethod
def create(report_type):
if report_type == "pdf":
return PDFReport()
elif report_type == "excel":
return ExcelReport()
elif report_type == "word":
return WordReport()
raise ValueError(f"不支持的报告类型: {report_type}")
# report = ReportFactory.create("pdf")
# ==================== 策略模式 ====================
class Sorter:
def __init__(self, strategy):
self.strategy = strategy
def sort(self, data):
return self.strategy(data)
# 不同排序策略
by_name = lambda users: sorted(users, key=lambda u: u["name"])
by_age = lambda users: sorted(users, key=lambda u: u["age"])
users = [{"name": "张三", "age": 30}, {"name": "李四", "age": 20}]
sorter = Sorter(by_age)
print(sorter.sort(users)) # 按年龄排序
代码协作管理(Git)
# ==================== Git 基本操作 ====================
git init # 初始化仓库
git add . # 暂存所有修改
git commit -m "feat: 添加用户模块" # 提交
git branch dev # 创建分支
git checkout dev # 切换分支
git merge dev # 合并分支
git remote add origin https://github.com/user/project.git
git push origin main # 推送
git pull origin main # 拉取
# ==================== .gitignore ====================
# 项目根目录创建 .gitignore 文件
__pycache__/
*.pyc
.env
venv/
*.log
output/
.idea/
依赖管理
# ==================== pip + requirements.txt ====================
pip install requests pandas # 安装
pip freeze > requirements.txt # 导出依赖
pip install -r requirements.txt # 安装依赖
# ==================== Poetry(现代依赖管理,推荐) ====================
pip install poetry
poetry init # 初始化项目
poetry add requests pandas # 添加依赖
poetry install # 安装所有依赖
poetry run python main.py # 在虚拟环境中运行
项目结构(标准模板)
my_project/
├── README.md # 项目说明文档
├── requirements.txt # 依赖清单
├── .gitignore # Git忽略文件
├── .env # 环境变量(不提交到Git)
├── config/ # 配置
│ ├── __init__.py
│ └── settings.py
├── src/ # 核心源码
│ ├── __init__.py
│ ├── models/ # 数据模型
│ ├── services/ # 业务逻辑
│ ├── utils/ # 工具函数
│ └── main.py # 入口
├── tests/ # 测试代码
│ ├── __init__.py
│ ├── test_models.py
│ └── test_services.py
├── docs/ # 文档
│ └── api.md
└── scripts/ # 脚本
└── deploy.sh
测试代码
# ==================== 单元测试 pytest ====================
# tests/test_calc.py
# 被测试的代码
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("除数不能为0")
return a / b
# --- 测试用例 ---
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_divide():
assert divide(10, 2) == 5.0
assert divide(7, 2) == 3.5
def test_divide_by_zero():
import pytest
with pytest.raises(ValueError):
divide(10, 0)
# 运行测试:
# pip install pytest
# pytest tests/ -v
# pytest tests/ -v --cov=src (带覆盖率报告)
18. 部署运维
Dockerfile
# ==================== Dockerfile ====================
FROM python:3.12-slim
WORKDIR /app
# 安装依赖(利用Docker缓存)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# 复制项目代码
COPY . .
# 环境变量
ENV PYTHONUNBUFFERED=1
# 启动命令
CMD ["python", "src/main.py"]
# 构建镜像
docker build -t my-python-app:1.0 .
# 运行容器
docker run -d --name my-app \
-e DB_HOST=192.168.1.100 \
-e DB_PASSWORD=secret \
-v /data/logs:/app/logs \
-p 5000:5000 \
my-python-app:1.0
# 查看日志
docker logs -f my-app
Docker Compose
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "5000:5000"
environment:
- DB_HOST=mysql
- REDIS_HOST=redis
depends_on:
- mysql
- redis
volumes:
- ./logs:/app/logs
restart: always
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root123
MYSQL_DATABASE: mydb
volumes:
- mysql_data:/var/lib/mysql
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
mysql_data:
docker-compose up -d # 启动所有服务
docker-compose logs -f app # 查看日志
docker-compose down # 停止所有服务
CI/CD(GitHub Actions 示例)
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 安装Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: 安装依赖
run: pip install -r requirements.txt
- name: 运行测试
run: pytest tests/ -v
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: 构建Docker镜像
run: docker build -t my-app:${{ github.sha }} .
- name: 部署
run: |
echo "部署到服务器..."
# ssh deploy@server "docker pull && docker-compose up -d"
监控告警
# ==================== 健康检查接口 ====================
from flask import Flask, jsonify
import psutil
app = Flask(__name__)
@app.route("/health")
def health_check():
"""健康检查端点,供监控系统调用"""
return jsonify({
"status": "healthy",
"cpu_percent": psutil.cpu_percent(),
"memory_percent": psutil.virtual_memory().percent,
"disk_percent": psutil.disk_usage('/').percent,
})
# ==================== 简单告警通知 ====================
import requests
def send_alert(title, content, level="warning"):
"""发送告警到企业微信/钉钉"""
# 企业微信机器人
webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx"
payload = {
"msgtype": "markdown",
"markdown": {
"content": f"## ⚠️ {title}\n\n"
f"**级别**: {level}\n\n"
f"**详情**: {content}\n\n"
f"**时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
}
}
requests.post(webhook, json=payload)
# 使用示例
if psutil.cpu_percent() > 90:
send_alert("CPU告警", f"CPU使用率超过90%: {psutil.cpu_percent()}%", "critical")
定时任务部署
# ==================== 定时调度 ====================
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
@scheduler.scheduled_job('cron', hour=8, minute=0)
def daily_report():
"""每天早上8点执行"""
print("生成日报...")
@scheduler.scheduled_job('cron', day_of_week='mon', hour=9)
def weekly_report():
"""每周一早上9点执行"""
print("生成周报...")
@scheduler.scheduled_job('interval', minutes=5)
def health_check():
"""每5分钟检查一次"""
print("健康检查...")
scheduler.start()
推荐学习资源
入门 《Python Crash Course》 经典入门
入门 《Automate the Boring Stuff》 实用自动化
进阶 《Fluent Python》⭐ 必读经典
进阶 《Effective Python》 90条建议
高级 《Python Cookbook》 食谱式参考
高级 《CPython Internals》 解释器源码
├── 官方文档:docs.python.org(最权威)
├── Real Python:realpython.com(高质量教程)
├── Python官方教程
├── LeetCode / 力扣(算法练习)
├── GitHub 开源项目阅读
└── PyCon 年会视频(YouTube)
Python 应用项目与实践类书籍大全
一、Python 基础与进阶
| 书名 | 作者 | 适合人群 | 说明 |
|---|---|---|---|
| 《Python编程:从入门到实践》 | Eric Matthes | 零基础 | 最推荐的入门书,含项目实战 |
| 《笨办法学Python 3》 | Zed Shaw | 零基础 | 通过练习驱动学习 |
| 《Python基础教程》 | Magnus Lie Hetland | 初级 | 经典入门,含10个项目 |
| 《流畅的Python》 | Luciano Ramalho | 中高级 | 深入Python高级特性 |
| 《Python Cookbook》 | David Beazley | 中高级 | 实用技巧和最佳实践 |
| 《Effective Python》 | Brett Slatkin | 中级 | 90条编程建议 |
| 《Python学习手册》 | Mark Luerta | 初中级 | 详尽的参考书 |
| 《Python核心编程》 | Wesley Chun | 中级 | 深入核心机制 |
| 《Python进阶》 | Yasoob | 中级 | 开源免费,进阶技巧 |
二、Web 开发
Django
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Django Web开发实战》 | 黄永祥 | 中文原创,实战项目 |
| 《Two Scoops of Django》 | Daniel/Audrey Feldroy | Django 最佳实践 |
| 《Django for Beginners》 | William S. Vincent | 3个完整项目 |
| 《Django for Professionals》 | William S. Vincent | 生产级项目部署 |
| 《Django for APIs》 | William S. Vincent | RESTful API 开发 |
| 《Test-Driven Development with Python》 | Harry Percival | TDD + Django 实践 |
Flask
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Flask Web开发实战》 | 李辉(greyli) | 中文原创,5个项目 |
| 《Flask Web开发》 | Miguel Grinberg | Flask 经典教材 |
| 《Building Web Apps with Python and Flask》 | Malhar Lathkar | 入门实战 |
FastAPI
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Building Python Web APIs with FastAPI》 | Abdulazeez Adeshina | FastAPI 实战 |
| 《Building Data Science Applications with FastAPI》 | François Voron | 数据科学+API |
三、数据科学与分析
| 书名 | 作者 | 说明 |
|---|---|---|
| 《利用Python进行数据分析》 | Wes McKinney | Pandas作者亲写,必读 |
| 《Python数据科学手册》 | Jake VanderPlas | NumPy/Pandas/Matplotlib/Scikit-learn |
| 《数据科学实战》 | Joel Grus | 从零构建数据科学工具 |
| 《Python数据分析与挖掘实战》 | 张良均 | 中文,14个案例 |
| 《Python数据可视化编程实战》 | Igor Milovanovic | Matplotlib 等可视化 |
| 《Storytelling with Data》 | Cole Knaflic | 数据可视化思维 |
| 《Python for Data Analysis》 | Wes McKinney | 第三版,更新至 Pandas 2.0 |
四、机器学习与深度学习
机器学习
| 书名 | 作者 | 说明 |
|---|---|---|
| 《机器学习实战》 | Peter Harrington | 经典入门,含代码实现 |
| 《Hands-On Machine Learning》 | Aurélien Géron | 最受欢迎的ML实战书 |
| 《Python Machine Learning》 | Sebastian Raschka | Scikit-learn 深度实战 |
| 《机器学习》 | 周志华 | 西瓜书,理论经典 |
| 《统计学习方法》 | 李航 | 理论+算法推导 |
| 《Feature Engineering for ML》 | Alice Zheng | 特征工程实战 |
深度学习
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Deep Learning with Python》 | François Chollet | Keras 作者亲写 |
| 《动手学深度学习》 | 李沐等 | 中文,MXNet/PyTorch/TF |
| 《PyTorch深度学习实战》 | Eli Stevens | PyTorch 入门到进阶 |
| 《深度学习入门:基于Python的理论与实现》 | 斋藤康毅 | 鱼书,从零实现神经网络 |
| 《TensorFlow实战Google深度学习框架》 | 郑泽宇 | TensorFlow 实战 |
| 《GANs in Action》 | Jakub Langr | 生成对抗网络实战 |
五、自然语言处理(NLP)
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python自然语言处理》 | Steven Bird | NLTK 官方教材 |
| 《Natural Language Processing with Transformers》 | Lewis Tunstall | Hugging Face 团队 |
| 《NLP实战:利用Python理解、分析和生成文本》 | Hobson Lane | 完整NLP项目 |
| 《Transformers for NLP》 | Denis Rothman | Transformer 架构实战 |
| 《基于BERT的自然语言处理》 | Naresh Kumar | BERT 应用开发 |
六、计算机视觉
| 书名 | 作者 | 说明 |
|---|---|---|
| 《OpenCV 4 with Python》 | Alberto Fernández | OpenCV 实战 |
| 《Python计算机视觉编程》 | Jan Erik Solem | 经典CV入门 |
| 《Deep Learning for Computer Vision》 | Rajalingappaa Shanmugamani | 深度学习+视觉 |
| 《Practical Python and OpenCV》 | Adrian Rosebrock | 快速上手 OpenCV |
七、网络爬虫
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python网络爬虫权威指南》 | Ryan Mitchell | 爬虫入门经典 |
| 《Python 3网络爬虫开发实战》 | 崔庆才 | 中文最全爬虫书,第2版 |
| 《精通Scrapy网络爬虫》 | 刘硕 | Scrapy 框架专精 |
| 《Python爬虫开发与项目实战》 | 范传辉 | 大量实战项目 |
八、自动化与运维
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python自动化运维》 | 刘天斯 | 运维实战经典 |
| 《Automate the Boring Stuff with Python》 | Al Sweigart | 办公自动化神书,免费在线 |
| 《Python for DevOps》 | Noah Gift | DevOps 实战 |
| 《Python自动化测试实战》 | 无涯 | Selenium/Appium 测试 |
| 《Python+Office:轻松实现办公自动化》 | 王秀文 | Excel/Word/PPT 自动化 |
九、网络编程与安全
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Black Hat Python》 | Justin Seitz | 黑客与渗透测试 |
| 《Violent Python》 | TJ O'Connor | 安全工具开发 |
| 《Python网络编程》 | Brandon Rhodes | 网络协议与编程 |
| 《Python黑帽子》 | Justin Seitz | 第2版,安全攻防 |
| 《Python绝技:运用Python成为顶级黑客》 | TJ O'Connor | 安全实战 |
十、游戏开发
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python游戏编程快速上手》 | Al Sweigart | Pygame 入门 |
| 《Making Games with Python & Pygame》 | Al Sweigart | 免费在线阅读 |
| 《Invent Your Own Computer Games with Python》 | Al Sweigart | 适合青少年 |
| 《Python编程:从入门到实践》第二部分 | Eric Matthes | 含外星人入侵游戏项目 |
十一、金融量化
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python for Finance》 | Yves Hilpisch | 量化金融经典 |
| 《量化投资:以Python为工具》 | 蔡立耑 | 中文量化入门 |
| 《Python金融大数据分析》 | Yves Hilpisch | 金融+数据分析 |
| 《Mastering Python for Finance》 | James Ma Weiming | 金融建模 |
| 《Python与量化投资》 | 王小川 | 策略开发实战 |
十二、科学计算与工程
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python科学计算》 | 张若愚 | 中文,NumPy/SciPy |
| 《Numerical Python》 | Robert Johansson | 科学计算深入 |
| 《Python for Scientists》 | John Stewart | 科研人员用 |
| 《Scipy and Numpy》 | Eli Bressert | 快速参考 |
十三、GUI 桌面应用
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python Qt GUI与数据可视化编程》 | 王维波 | PyQt5 实战 |
| 《Rapid GUI Programming with Python and Qt》 | Mark Summerfield | Qt 经典 |
| 《wxPython in Action》 | Noel Rappin | wxPython 开发 |
| 《Create GUI Applications with Python & Qt》 | Martin Fitzpatrick | PyQt6/PySide6 |
十四、DevOps / 微服务 / 云
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python微服务开发》 | Tarek Ziadé | 微服务架构 |
| 《Architecture Patterns with Python》 | Harry Percival | 领域驱动设计 |
| 《Infrastructure as Code with Python》 | Moshe Zadka | 基础设施自动化 |
| 《Python for DevOps》 | Noah Gift | CI/CD + 云原生 |
十五、物联网 / 树莓派 / 硬件
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python树莓派编程》 | Simon Monk | 硬件+Python |
| 《Raspberry Pi Cookbook for Python Programmers》 | Tim Cox | 树莓派项目 |
| 《MicroPython入门指南》 | 多作者 | 嵌入式 Python |
| 《Programming with MicroPython》 | Nicholas Tollervey | 物联网开发 |
十六、设计模式与架构
| 书名 | 作者 | 说明 |
|---|---|---|
| 《Python设计模式》 | Chetan Giridhar | 经典设计模式 |
| 《Architecture Patterns with Python》 | Harry Percival | DDD + 事件驱动 |
| 《Robust Python》 | Patrick Viafore | 类型注解+健壮代码 |
| 《Practices of the Python Pro》 | Dane Hillard | 专业代码组织 |
| 《Clean Code in Python》 | Mariano Anaya | Python 代码整洁之道 |
推荐学习路线
第一阶段(入门)
📖 《Python编程:从入门到实践》
📖 《Automate the Boring Stuff with Python》
↓
第二阶段(进阶)
📖 《流畅的Python》
📖 《Effective Python》
📖 《Python Cookbook》
↓
第三阶段(选择方向深入)
🌐 Web → 《Flask/Django Web开发》
🤖 AI/ML → 《Hands-On Machine Learning》
🕷️ 爬虫 → 《Python 3网络爬虫开发实战》
📊 数据 → 《利用Python进行数据分析》
🔒 安全 → 《Black Hat Python》
💰 量化 → 《Python for Finance》
🤖 自动化 → 《Automate the Boring Stuff》
↓
第四阶段(架构与工程化)
📖 《Architecture Patterns with Python》
📖 《Clean Code in Python》
📖 《Robust Python》
提示:以上大部分英文书籍都有中文翻译版。建议优先选择最新版,因为 Python 生态更新较快,旧版内容可能已过时。
浙公网安备 33010602011771号