大学计算机专业 · Python 程序设计(Python 3.10 / 3.11 / 3.12)

Python 程序设计:
语法基础到 AI 应用的完整学习教程

本教程面向大学一年级学生,从语法基础 → 数据结构 → 函数与模块 → 面向对象 → 文件与异常 → Python 高级特性 → 标准库 → 工具与工程化 → 数据分析 / AI 方向 → 综合项目。完成后你将能独立用 Python 完成脚本、爬虫、数据分析,乃至 AI 应用开发

1991Guido van Rossum 发布 Python
解释型无需编译,交互式运行
Python 3.12当前主流稳定版本
AI / 数据科学NumPy · Pandas · PyTorch
↓ 向下滚动,按章节系统学习。学完基础后可分流到 数据科学 / Web / AI 方向
00

学习指南:为什么学、怎么学、学到什么

Python 是最易学、最强大的通用语言之一,也是 AI / 数据科学的事实标准。

00.1 什么是 Python

Python 由 Guido van Rossum1989 年开始设计,1991 年首次发布。它是一门解释型、动态类型、面向对象的高级语言。

Python 的核心特点

  • 语法简洁优雅:用缩进而非括号,接近自然语言;
  • 动态类型:无需声明变量类型;
  • 解释执行:无需编译,交互式运行;
  • 多范式:面向对象、函数式、过程式;
  • 丰富标准库与第三方库:"电池自带" + PyPI 50万+ 包;
  • 跨平台:Windows / macOS / Linux 全支持。

Python 应用领域

  • AI / 机器学习:PyTorch、TensorFlow、Scikit-learn;
  • 数据科学:Pandas、NumPy、Matplotlib;
  • Web 开发:Django、Flask、FastAPI;
  • 自动化 / 脚本:运维、办公自动化;
  • 爬虫 / 数据采集:requests、Scrapy;
  • 科学计算 / 教学:MIT、Stanford 等采用。

一句话总结:Python 是"易学 + 强大"的代名词 —— 用最少代码做最多事,是 AI 时代的入门首选。

00.2 五阶段学习路线(学完基础后可分流)

Python 基础第 01-09 章
程序设计第 10-13 章
Python 核心第 14-19 章
应用方向第 20-26 章
专业方向第 27-30 章
综合项目第 31 章

学完基础后的三条分流路线

🧮 数据科学
NumPy · Pandas · Matplotlib · Scikit-learn
🌐 Web 开发
Flask · FastAPI · Django · 数据库
🤖 人工智能
PyTorch · API · AI Agent · LLM

00.3 Python 与其他语言的对比

特性PythonCC++Java
类型动态静态静态静态
执行解释型编译型编译型JVM 字节码
内存管理自动(GC)手动手动 / 智能指针自动(GC)
运行速度最快接近 C中等
学习曲线平缓中等
应用领域AI / 数据 / 脚本系统 / 嵌入式系统 / 游戏企业级后端
01

Python 入门:安装与第一个程序

Python 安装简单,三行代码就能写出一个完整程序。

1.1 安装 Python

平台方法
Windows官网 python.org 下载安装包;勾选 "Add Python to PATH"
macOSbrew install python3(推荐)或官网 pkg
Linux通常自带,或 sudo apt install python3
shell验证安装
# 检查版本
$ python3 --version
Python 3.12.0

# 进入交互式解释器
$ python3
>>> 2 + 3
5
>>> print("Hello")
Hello
>>> exit()

1.2 第一个 Python 程序

Pythonhello.py
# hello.py —— 最简单的 Python 程序
print("Hello, World!")
shell运行
$ python3 hello.py
Hello, World!

1.3 主流 IDE

VS Code(推荐入门)

  • 微软出品,免费跨平台;
  • 安装 "Python" 扩展;
  • 轻量,调试方便;
  • 适合脚本、Web 项目。

PyCharm(专业 Python IDE)

  • JetBrains 出品,Python 专业 IDE;
  • Community 版免费;
  • 智能补全、调试、虚拟环境管理;
  • 适合大型项目。
数据科学方向:推荐 Jupyter Notebook(pip install jupyter),逐块运行 + 富文本 + 可视化,AI 教学首选。
02

Python 基本语法:缩进、注释与标识符

Python 最与众不同的语法:用缩进代替大括号 —— 简洁却严格。

2.1 缩进:Python 的灵魂 必须

Python 用相同缩进表示同一代码块(其他语言用 { }):

Pythonindent.py
if score >= 60:
    print("及格")
    print("加油")
else:
    print("不及格")

# 缩进不一致会报错
# IndentationError: unexpected indent
规范:每级缩进4 个空格(PEP 8)。不要混用 Tab 和空格(多数 IDE 会自动转换)。

2.2 注释与多行字符串

Pythoncomments.py
# 单行注释:以 # 开头

"""
多行字符串 / 文档字符串(docstring):
- 模块、类、函数的首行可以用三引号说明
- 可以通过 __doc__ 访问
"""

def add(a, b):
    """返回 a + b 的和"""
    return a + b

2.3 标识符与关键字

Python 关键字约 35 个(Python 3.12):

FalseNoneTrueandasassertasyncawaitbreakclasscontinuedefdelelifelseexceptfinallyforfromglobalifimportinislambdanonlocalnotorpassraisereturntrywhilewithyieldmatchcase

命名规范:变量/函数 snake_case;类 PascalCase;常量 UPPER_SNAKE

03

变量、动态类型与运算符

Python 是动态类型:变量没有类型,值有类型。同一个变量可以随时指向不同类型的值。

3.1 变量与基本类型

Pythontypes.py
# 整数 int
age = 18

# 浮点 float
score = 95.5

# 复数 complex
z = 1 + 2j

# 字符串 str
name = "Python"

# 布尔 bool
ok = True

# 空值 NoneType
result = None

# 动态类型:变量可随时指向新类型
x = 10
x = "hello"      # ✔ OK

3.2 类型判断与转换

Pythoncast.py
x = 3.14

type(x)              # <class 'float'>
isinstance(x, float)  # True(推荐)

# 显式转换
int("123")         # 123
float("3.14")     # 3.14
str(42)           # '42'
bool(0)           # False
list("abc")       # ['a', 'b', 'c']

3.3 运算符

类别运算符
算术+ - * / // % **(// 整除,** 幂)
比较== != > < >= <=
逻辑and or not(英文单词)
成员in · not in
身份is · is not
位运算& | ^ ~ << >>
Pythonoperator.py
# Python 特有的
7 / 2     # 3.5(真除法)
7 // 2    # 3(整除,向下取整)
2 ** 10   # 1024

# 链式比较
1 < x < 10     # ✔ Python 支持链式比较

# 海象运算符(Python 3.8+)
if (n := len(name)) > 5:
    print(n)
is vs ==:== 比较"值相等";is 比较"是不是同一个对象"。判断 None 必须用 is None

课堂练习 · 第03章

1表达式 7 / 27 // 2 的结果分别是?
2判断变量 x 是否为 None,正确的写法是?
04

字符串 ⭐

字符串是 Python 使用最频繁的类型之一 —— 切片、f-string、各种方法都极为强大。

4.1 创建与索引

Pythonstr.py
s = "Python"
s[0]      # 'P'   (正向)
s[-1]     # 'n'   (反向)

# 多行字符串
text = """第一行
第二行
第三行"""

# 转义
s = "他说:\"你好\""
print("a\nb")   # 换行
print(r"C:\Users")  # 原始字符串,不转义

4.2 切片 [start:end:step] ⭐⭐⭐

Pythonslice.py
s = "Hello, World!"

s[0:5]       # 'Hello'    (包头不包尾)
s[7:]        # 'World!'   (从 7 到最后)
s[:-1]      # 'Hello, World' (去掉最后)
s[::2]      # 'Hlo ol!'   (步长 2)
s[::-1]     # '!dlroW ,olleH' (反转)

记忆口诀:"包头不包尾,负数反向走"。切片是 Python 数据处理的灵魂。

4.3 f-string 格式化 Python 3.6+

Pythonfstring.py
name = "Tom"
age = 20
pi = 3.14159

print(f"姓名:{name}, 年龄:{age}")             # 姓名:Tom, 年龄:20
print(f"PI 保留两位:{pi:.2f}")          # 3.14
print(f"十六进制:{255:#x}")            # 0xff
print(f"右对齐:{'hi':>10}|")      # '        hi|'

# 表达式与调试 = (Python 3.8+)
print(f"{name=}, {age=}")            # name='Tom', age=20

4.4 常用字符串方法

方法作用
len(s)长度
s.upper() / s.lower()大小写转换
s.strip() / s.lstrip() / s.rstrip()去首尾空白
s.split(sep)拆分成列表
sep.join(list)用分隔符拼接列表
s.replace(old, new)替换
s.find(sub) / s.index(sub)查找(找不到 -1 / 抛异常)
s.startswith(p) / s.endswith(p)前缀/后缀
s.count(sub)出现次数
s.isdigit() / s.isalpha() / s.isspace()字符判断
字符串不可变:所有"修改"方法都返回新字符串,原字符串不变。如需高效拼接大量字符串,用 str.join()io.StringIO
05

列表 ⭐⭐⭐ —— 最常用的数据结构

列表(list)是 Python 的主力容器:有序、可变、支持任意类型元素。

5.1 创建、索引、切片

Pythonlist.py
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, [1, 2]]    # 元素类型可以混合

nums[0]          # 1
nums[-1]         # 5(最后一个)
nums[1:4]        # [2, 3, 4]
nums[::2]        # [1, 3, 5]
nums[::-1]       # [5, 4, 3, 2, 1](反转)

len(nums)        # 5
nums[0] = 100      # ✔ 可修改

5.2 增删改

Pythonlist_ops.py
a = [1, 2, 3]

# 添加
a.append(4)             # [1,2,3,4]
a.extend([5, 6])         # [1,2,3,4,5,6]
a.insert(1, 99)         # [1,99,2,3,4,5,6]

# 删除
a.remove(99)            # 按值删第一个 99
a.pop()                 # 删末尾,返回值
a.pop(0)               # 删第一个
del a[0]              # 按下标删
a.clear()               # 清空 → []

# 排序
a.sort()                # 升序,原地
a.sort(reverse=True)   # 降序
sorted(a)             # 返回新列表,原列表不变

5.3 列表推导式 ⭐⭐⭐

Pythoncomprehension.py
# 1~10 的平方
squares = [x * x for x in range(1, 11)]

# 偶数
evens = [x for x in range(10) if x % 2 == 0]

# 嵌套:二维拍平
matrix = [[1,2], [3,4], [5,6]]
flat = [x for row in matrix for x in row]   # [1,2,3,4,5,6]
性能:列表推导式比等价的 for 循环快约 30%。但嵌套不超过 2 层,否则可读性下降。
06

元组、集合与字典 ⭐⭐⭐

Python 内置容器的"全家福":tuple(不可变序列)、set(去重)、dict(键值映射)。

6.1 元组 tuple:不可变序列

Pythontuple.py
point = (10, 20)
x, y = point       # 解包

# 单元素元组必须有逗号
t = (42,)         # tuple
t = (42)          # int

# 不可变:
# point[0] = 99    # ❌ TypeError

# 常见用途:作为字典的 key、函数多返回值
def minmax(arr):
    return min(arr), max(arr)

mn, mx = minmax([3, 1, 4, 1, 5, 9, 2, 6])

6.2 集合 set:去重 + 集合运算

Pythonset.py
s = {1, 2, 3, 2, 1}
print(s)        # {1, 2, 3}   自动去重

s.add(4)
s.remove(1)        # 不存在会抛异常
s.discard(1)      # 不存在静默

# 集合运算
a = {1, 2, 3}
b = {3, 4, 5}
a | b          # {1,2,3,4,5}  并集
a & b          # {3}         交集
a - b          # {1, 2}      差集
a ^ b          # {1,2,4,5}   对称差

6.3 字典 dict ⭐⭐⭐

Pythondict.py
student = {
    "name": "Tom",
    "age": 20,
    "score": 95,
}

# 增删改查
student["gender"] = "M"          # 添加
student["age"] = 21              # 修改
v = student.get("name", "N/A")     # 安全访问
del student["gender"]

# 遍历
for k, v in student.items():
    print(k, v)

# 字典推导式
squares = {x: x*x for x in range(5)}    # {0:0, 1:1, 2:4, 3:9, 4:16}
字典顺序:Python 3.7+ 字典保持插入顺序。
07

程序控制结构:if / while / for / match

Python 用缩进组织代码块;新增的 match-case 让多分支更简洁。

7.1 if / elif / else

Pythonif.py
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 60:
    print("C")
else:
    print("D")

# 三元表达式
msg = "及格" if score >= 60 else "不及格"

7.2 match-case Python 3.10+

Pythonmatch.py
command = "quit"

match command:
    case "quit":
        print("退出")
    case "save" | "export":        # 多值
        print("保存")
    case var if var.startswith("load"):    # 守卫
        print("加载", var)
    case _:                              # 默认
        print("未知")

7.3 while / for / range

Pythonloop.py
# while
n = 0
while n < 5:
    print(n)
    n += 1

# for + range
for i in range(5):          # 0..4
    print(i)

range(2, 10, 3)        # 2, 5, 8
range(10, 0, -1)      # 10..1

# 遍历列表 / 字典
for x in [1, 2, 3]:
    print(x)

for i, v in enumerate(["a", "b", "c"]):     # (0,a), (1,b), (2,c)
    print(i, v)

7.4 综合案例:九九乘法表

Python9x9.py
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}×{i}={i*j:<2}", end=" ")
    print()

课堂练习 · 第07章

3for i in range(5): print(i) 的输出是?
4match-case 语句是 Python 哪个版本引入的?
08

函数 ⭐⭐⭐

Python 函数是一等公民:可以赋值给变量、作为参数传递、作为返回值。

8.1 定义与参数

Pythonfunc.py
def greet(name, greeting="Hello"):     # 默认参数
    return f"{greeting}, {name}!"

greet("Tom")                      # Hello, Tom!
greet("Tom", greeting="Hi")        # Hi, Tom!

# 关键字参数
greet(greeting="Hey", name="Alice")

# *args / **kwargs:可变参数
def add(*args, **kwargs):
    print(args)      # tuple (1, 2, 3)
    print(kwargs)    # dict {x: 1, y: 2}

add(1, 2, 3, x=1, y=2)

8.2 作用域与闭包

Pythonscope.py
x = "global"

def outer():
    x = "enclosing"

    def inner():
        nonlocal x        # 修改外层(非全局)变量
        x = "local"

    inner()
    print(x)        # local

outer()

# global 关键字:声明使用全局变量
counter = 0
def inc():
    global counter
    counter += 1

8.3 函数作为对象 + 递归

Pythonfirst_class.py
# 函数是一等公民
f = abs
print(f(-5))      # 5

# 高阶函数:接受函数作为参数
def apply(func, x, y):
    return func(x, y)

print(apply(lambda a, b: a * b, 3, 4))   # 12

# 递归
def factorial(n):
    if n <= 1: return 1
    return n * factorial(n - 1)
09

推导式与生成式

Python 的招牌特性:用一行代码完成循环 + 过滤 + 映射。

9.1 列表推导式

Pythoncomp.py
# 基本:[表达式 for 变量 in 可迭代对象]
squares = [x * x for x in range(10)]

# 条件:[表达式 for x in ... if 条件]
evens = [x for x in range(10) if x % 2 == 0]

# 多层 for
pairs = [(x, y) for x in [1, 2, 3] for y in ["a", "b"]]

9.2 字典 / 集合推导式 + 生成器表达式

Pythondict_comp.py
# 字典
counts = {ch: s.count(ch) for ch in set(s)}

# 集合
unique = {x % 3 for x in range(10)}

# 生成器表达式(惰性、按需产出,节省内存)
gen = (x * x for x in range(1000000))
print(sum(gen))   # 不需要先存列表

何时用哪种?需要多次使用/知道长度 → 列表;数据量大、只用一次 → 生成器表达式。

10

模块与包

Python 的代码组织单元:模块 (.py 文件) → 包(带 __init__.py 的目录)。

10.1 import 方式

Pythonimport_demo.py
import math
import numpy as np
from math import sqrt, pi
from os.path import join

print(math.sqrt(16))
print(np.array([1, 2, 3]))

10.2 if __name__ == "__main__" 模式

Pythonmain.py
# utils.py
def add(a, b):
    return a + b

if __name__ == "__main__":
    # 仅当直接运行此文件时执行,被 import 时不会
    print(add(3, 5))
意义:让一个 .py 文件既能作为脚本直接运行,又能作为模块被其他文件 import —— 不会重复执行测试代码。
11

文件与数据读写

Python 用内置 open() + with 处理文件;JSON/CSV 用标准库。

11.1 文本文件读写

Pythonfile.py
# 读取整个文件
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

# 逐行读取(生成器)
with open("data.txt") as f:
    for line in f:        # 每行保留 \n
        print(line.rstrip())

# 写入
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

# 推荐:pathlib
from pathlib import Path
text = Path("data.txt").read_text(encoding="utf-8")
Path("out.txt").write_text("hello", encoding="utf-8")

11.2 JSON 与 CSV

Pythondata_io.py
import json

# 对象 ↔ JSON
data = {"name": "Tom", "age": 20}
s = json.dumps(data, ensure_ascii=False)    # → JSON 字符串
obj = json.loads(s)                         # ← JSON 字符串

import csv
with open("data.csv", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])
12

异常处理 ⭐⭐

Python 的EAFP 风格:"先做了再说,报错了再处理" —— 与 Java 的 LBYL 形成对比。

12.1 try / except / else / finally

Pythontry.py
try:
    n = int(input("数字:"))
    result = 10 / n
except ValueError:
    print("请输入数字")
except ZeroDivisionError:
    print("不能为零")
except (TypeError, KeyError) as e:
    print(f"其他错误:{e}")
else:
    print("无异常,结果:", result)
finally:
    print("结束")

12.2 raise / 自定义异常

Pythonraise.py
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        super().__init__(f"余额 {balance}, 需 {amount}")
        self.balance = balance

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount
13

面向对象编程 ⭐⭐⭐

Python 的 OOP 简洁优雅 —— 没有 public/private 关键字,用下划线约定表达意图。

13.1 类与对象

Pythonstudent.py
class Student:
    """学生类"""

    # 构造方法
    def __init__(self, name: str, age: int, score: float = 0.0):
        self.name = name      # 实例属性
        self._age = age        # 单下划线:约定"内部使用"
        self.score = score

    def study(self, subject: str) -> None:
        print(f"{self.name} 正在学 {subject}")

    def __repr__(self) -> str:
        return f"Student(name={self.name}, age={self._age})"

# 使用
s = Student("Alice", 20, 95.5)
s.study("Python")
print(s)              # Student(name=Alice, age=20)

13.2 封装与属性 @property

Pythonproperty.py
class Account:
    def __init__(self, balance):
        self._balance = balance

    # @property:把方法变成属性(getter)
    @property
    def balance(self):
        return self._balance

    # setter
    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("不能为负")
        self._balance = value

a = Account(100)
print(a.balance)      # 100(像属性一样访问)
a.balance = 200      # 自动走 setter

13.3 继承、方法重写、super()

Pythoninherit.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hi(self):
        print(f"Hi, I'm {self.name}")

class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)    # 调用父类
        self.school = school

    def say_hi(self):                  # 方法重写
        super().say_hi()
        print(f"I study at {self.school}")

s = Student("Alice", 20, "MIT")
s.say_hi()

13.4 多态、类方法、静态方法

Pythonpoly.py
# Python 的多态:鸭子类型 —— 只要有方法就能用
class Dog:
    def speak(self): print("汪")

class Cat:
    def speak(self): print("喵")

def make_speak(animal):
    animal.speak()

make_speak(Dog())   # 汪
make_speak(Cat())   # 喵

# 类方法、静态方法
class Circle:
    pi = 3.14159

    def __init__(self, r): self.r = r

    @classmethod
    def from_diameter(cls, d):
        return cls(d / 2)

    @staticmethod
    def is_valid_radius(r):
        return r > 0

13.5 魔术方法(Magic Methods) ⭐

Pythonmagic.py
class Vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):       # 调试字符串
        return f"Vec2({self.x}, {self.y})"

    def __str__(self):        # 用户友好字符串
        return f"(<{self.x}, {self.y}>)"

    def __add__(self, other):  # +
        return Vec2(self.x + other.x, self.y + other.y)

    def __eq__(self, other):  # ==
        return self.x == other.x and self.y == other.y

    def __len__(self):       # len()
        return 2

    def __getitem__(self, i): # 下标访问
        return [self.x, self.y][i]

v = Vec2(3, 4)
print(v + Vec2(1, 2))    # Vec2(4, 6)
print(v[0])              # 3
print(len(v))             # 2

常用魔术方法:__init__ / __str__ / __repr__ / __len__ / __getitem__ / __iter__ / __eq__ / __lt__ / __add__ / __enter__ / __exit__

课堂练习 · 第13章 OOP

5关于 @property,正确的是?
6Python 中"私有属性"的实现方式是?
14

迭代器与生成器 ⭐⭐

Python 的惰性求值机制 —— 节省内存、处理无限序列。

14.1 生成器函数 yield

Pythongen.py
def counter(n):
    for i in range(n):
        yield i           # 暂停,返回值;下次 next() 时继续

g = counter(5)
print(next(g))      # 0
print(next(g))      # 1
for x in g:           # 继续迭代剩下的
    print(x)

# 生成器表达式(与列表推导式类似)
gen = (x * x for x in range(10 if x % 2 == 0)
print(sum(gen))    # 0+4+16+36+64 = 120
优势:生成器只在需要时计算下一个值,适合处理大文件、无限序列、网络流。

14.2 自定义迭代器

Pythoniter.py
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):       # 返回迭代器
        return self

    def __next__(self):       # 下一个值
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for i in Countdown(3):    # 3, 2, 1
    print(i)
15

Lambda 与函数式编程

Python 也支持函数式风格:map / filter / reduce + Lambda。

15.1 Lambda + map / filter / sorted

Pythonlambda.py
square = lambda x: x * x
print(square(5))        # 25

# map: 对每个元素应用函数
nums = [1, 2, 3, 4]
sq = list(map(lambda x: x * x, nums))   # [1, 4, 9, 16]

# filter: 过滤
evens = list(filter(lambda x: x % 2 == 0, nums))

# sorted + key
students = [{"name": "Tom", "score": 85}, {"name": "Alice", "score": 95}]
sorted(students, key=lambda s: s["score"], reverse=True)

# reduce(functools)
from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3, 4]))   # 10
16

装饰器 ⭐⭐

Python 的"黑魔法"之一:在不修改原函数代码的前提下,给函数"加上新能力"。

16.1 基础装饰器

Pythondecorator.py
def timer(func):
    """计时装饰器"""
    def wrapper(*args, **kwargs):
        import time
        t0 = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} 用时 {time.time() - t0}s")
        return result
    return wrapper

@timer
def slow():
    sum(range(1000000))

slow()    # slow 用时 0.03s

16.2 带参数的装饰器 + functools.wraps

Pythonparam_deco.py
def retry(times=3):
    def decorator(func):
        from functools import wraps
        @wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(times):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if i == times - 1: raise
        return wrapper
    return decorator

@retry(times=3)
def flaky_network_call():
    # ...
    pass
不要忘记 @functools.wraps(func) —— 否则原函数的 __name__、__doc__ 会被 wrapper 覆盖。
17

正则表达式 re

Python 内置的 re 模块让你用一行代码完成复杂的字符串匹配。

17.1 常用函数与示例

Pythonregex.py
import re

text = "联系我:[email protected] 或 138-1234-5678"

# 提取邮箱
emails = re.findall(r"[\w.]+@[\w.]+", text)

# 提取手机号
phones = re.findall(r"\d{3}-\d{4}-\d{4}", text)

# 替换
masked = re.sub(r"\d", "*", "我的卡号是 1234-5678")

# 校验格式
def is_email(s):
    return re.match(r"^[\w.]+@[\w.]+\.\w+$", s) is not None
18

日期时间 datetime

datetimetimedelta 处理日期、时间差、格式化。

18.1 datetime 基础

Pythondatetime.py
from datetime import datetime, date, timedelta

now = datetime.now()
today = date.today()

# 构造与格式化
dt = datetime(2024, 3, 15, 10, 30)
s = dt.strftime("%Y-%m-%d %H:%M:%S")

# 解析
parsed = datetime.strptime("2024-03-15", "%Y-%m-%d")

# 时间差
delta = timedelta(days=7, hours=2)
next_week = now + delta

# 时间戳
ts = now.timestamp()           # 1742025667.123
dt2 = datetime.fromtimestamp(ts)
19

Python 标准库速查中心 ⭐⭐

Python "自带电池"(batteries included)—— 下列标准库几乎覆盖日常所有需求。

常用标准库速查表

模块作用
math数学函数(sin / cos / sqrt / log)
random随机数(random / randint / choice / shuffle)
statistics统计(mean / median / stdev)
datetime日期时间
os操作系统接口(path / environ / listdir)
sys解释器交互(argv / exit / path)
pathlib面向对象的文件路径
shutil高级文件操作(copy / move / rmtree)
jsonJSON 编解码
csvCSV 读写
re正则表达式
collections特殊容器(Counter / deque / OrderedDict / defaultdict)
itertools迭代器工具(chain / cycle / combinations)
functools高阶函数(reduce / lru_cache / partial)
logging日志记录
subprocess运行外部命令
argparse命令行参数解析
sqlite3内置 SQLite 数据库
threading线程
asyncio异步 IO
20

pip 与虚拟环境 ⭐⭐⭐

管理第三方包、隔离项目依赖 —— Python 工程化的"基础设施"。

20.1 pip 基础

shellpip
# 安装 / 卸载 / 升级
$ pip install requests
$ pip install requests==2.31.0     # 指定版本
$ pip install -r requirements.txt  # 从文件安装
$ pip install --upgrade numpy
$ pip uninstall pandas

# 查看 / 导出
$ pip list
$ pip show numpy
$ pip freeze > requirements.txt    # 导出依赖

20.2 虚拟环境 venv

shellvenv
# 创建虚拟环境
$ python3 -m venv .venv

# 激活
$ source .venv/bin/activate          # macOS / Linux
$ .venv\Scripts\activate            # Windows

# 在虚拟环境中安装包
(venv) $ pip install requests

# 退出
(venv) $ deactivate
现代推荐:uvpoetry 替代 venv + pip —— 速度更快、依赖锁定更智能。
21

类型注解 Type Hints

Python 是动态类型,但类型注解让 IDE、mypy、运行期都能给你更好的提示。

21.1 变量与函数注解

Pythontyping.py
name: str = "Tom"
age: int = 20
scores: list[int] = [90, 85, 95]

def add(a: int, b: int) -> int:
    return a + b

# 复杂类型
from typing import Optional, Union

def find_user(uid: int) -> Optional[str]:
    return None     # 或 str

def parse(x: Union[int, str]) -> int:
    return int(x)
22

多线程与并发

Python 因GIL的存在,CPU 密集任务用多进程,IO 密集任务用多线程 / asyncio。

22.1 threading + Lock

Pythonthread.py
import threading

counter = 0
lock = threading.Lock()

def worker():
    global counter
    for _ in range(10000):
        with lock:           # 互斥访问
            counter += 1

threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()

print(counter)   # 40000

22.2 concurrent.futures:线程池 ⭐

Pythonpool.py
from concurrent.futures import ThreadPoolExecutor

def fetch(url):
    # 模拟网络请求
    return f"data from {url}"

urls = [f"https://api.example.com/{i}" for i in range(10)]

with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(fetch, urls))
23

异步编程 asyncio ⭐⭐

现代 Python 必备 ——协程让 IO 密集型程序效率倍增。

23.1 async / await 基础

Pythonasync.py
import asyncio

async def fetch(url):
    print(f"Fetching {url}...")
    await asyncio.sleep(1)        # 模拟 IO
    print(f"Done {url}")
    return f"data from {url}"

async def main():
    # 并发执行 3 个任务
    results = await asyncio.gather(
        fetch("a.com"),
        fetch("b.com"),
        fetch("c.com"),
    )

asyncio.run(main())

23.2 aiohttp 异步 HTTP 请求

Pythonaiohttp.py
import aiohttp
import asyncio

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [session.get(u) for u in urls]
        responses = await asyncio.gather(*tasks)
        return [r.text() async for r in responses]
24

网络编程

requests 调用 HTTP API、用 socket 实现自定义协议。

requests 库 ⭐⭐⭐

Pythonrequests_demo.py
import requests

# GET 请求
r = requests.get("https://api.github.com/users/python")
print(r.json()["name"])

# 带参数 + POST
data = {"name": "Tom", "age": 20}
r = requests.post("https://httpbin.org/post", json=data, timeout=5)

# 错误处理
try:
    r.raise_for_status()      # 4xx / 5xx 自动抛异常
except requests.HTTPError as e:
    print(e)
25

JSON、CSV 与数据交换

数据交换的两大格式 —— 数据科学 / API 通信必备。

JSON 与 CSV 实战

Pythonjson_csv.py
import json, csv

# JSON
data = {"users": [{"name": "Tom", "age": 20}]}
print(json.dumps(data, indent=2, ensure_ascii=False))

# CSV:DictReader
with open("data.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])
26

数据库:SQLite 与 SQL 基础

Python 内置 sqlite3 —— 无需额外安装就能用 SQL。

sqlite3 CRUD

Pythondb.py
import sqlite3

conn = sqlite3.connect("school.db")
c = conn.cursor()

# 创建表
c.execute("""CREATE TABLE IF NOT EXISTS student(
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER)""")

# 插入(参数化防 SQL 注入)
c.execute("INSERT INTO student(name, age) VALUES(?, ?)", ("Tom", 20))
conn.commit()

# 查询
for row in c.execute("SELECT * FROM student WHERE age > ?", (18,)):
    print(row)

conn.close()
27

Python 工程化:项目结构、测试与日志

从"会写脚本"升级到"能交付项目":规范、测试、日志、配置。

项目结构

treeproject/
my_project/
├── pyproject.toml     # 现代项目配置(替代 setup.py)
├── README.md
├── .gitignore
├── requirements.txt
├── src/
│   └── myapp/
│       ├── __init__.py
│       ├── main.py
│       └── utils.py
├── tests/
│   ├── __init__.py
│   └── test_main.py
└── data/
    └── input.csv

pytest 单元测试

Pythontest_main.py
from myapp.utils import add

def test_add():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, 1) == 0
28

数据分析基础 ⭐⭐⭐ —— NumPy / Pandas / Matplotlib

Python 在数据科学领域的事实标准三件套。

28.1 NumPy:高性能数组计算

Pythonnumpy.py
import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(a + 10)                # [11 12 13 14 15](向量化)
print(a.mean(), a.std())

# 二维数组(矩阵)
m = np.array([[1, 2], [3, 4]])
print(m.T)         # 转置
print(m @ m)       # 矩阵乘法

28.2 Pandas:数据分析的核心

Pythonpandas.py
import pandas as pd

# 读 CSV
df = pd.read_csv("students.csv")

print(df.head())            # 前 5 行
print(df.describe())        # 数值列统计
print(df.info())            # 数据类型概览

# 筛选、排序
adults = df[df["age"] >= 18]
top = df.sort_values("score", ascending=False)

# 分组统计
avg_by_class = df.groupby("class")["score"].mean()

28.3 Matplotlib:可视化

Pythonplot.py
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)

plt.figure(figsize=(8, 4))
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend()
plt.title("三角函数")
plt.savefig("trig.png", dpi=100)
plt.show()
29

Python 与人工智能 ⭐⭐

Python 是 AI 时代的事实标准语言。本章带你入门 ML / DL / LLM。

29.1 Scikit-learn:传统机器学习

Pythonsklearn.py
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = RandomForestClassifier()
model.fit(X_train, y_train)
pred = model.predict(X_test)

print("准确率:", accuracy_score(y_test, pred))

29.2 调用 AI API(OpenAI / Anthropic / 国内大模型)

Pythonai_api.py
import openai

client = openai.OpenAI(api_key="sk-xxx")

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "你是一个 Python 助手"},
        {"role": "user", "content": "什么是列表推导式?"},
    ],
)
print(response.choices[0].message.content)
30

数据结构与算法

Python 的简洁语法让"算法实现"特别清爽 —— 但仍要重视效率。

30.1 常见复杂度 + 二分查找

Pythonbinary_search.py
import bisect

a = [1, 3, 5, 7, 9, 11]

# 二分查找(标准库)
bisect.bisect_left(a, 7)      # 3(第一个 ≥ 7 的位置)
bisect.bisect_right(a, 7)     # 4(第一个 > 7 的位置)

# 手写二分
def bsearch(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:   return mid
        elif a[mid] < target: lo = mid + 1
        else:                hi = mid - 1
    return -1

30.2 单链表 + 排序 + 递归

Pythonalgo.py
# 链表节点
class Node:
    def __init__(self, v, n=None):
        self.v, self.n = v, n

# 快速排序
def qsort(a):
    if len(a) <= 1: return a
    p = a[0]
    return qsort([x for x in a[1:] if x < p]) + [p] + \
           qsort([x for x in a[1:] if x >= p])

print(qsort([5, 2, 8, 1, 9, 3]))   # [1, 2, 3, 5, 8, 9]

# 实战建议:直接用 sorted()
print(sorted([5, 2, 8, 1, 9, 3]))   # [1, 2, 3, 5, 8, 9]
31

综合项目:从练习到作品

8 个递进项目,覆盖 Python 的常见应用场景。

项目一:猜数字游戏 🎲

难度 ★☆☆ · 变量 / if / while / random
Pythonguess.py
import random

target = random.randint(1, 100)
tries = 0

while True:
    n = int(input("猜一个 1-100 的数:"))
    tries += 1
    if n > target:      print("大了")
    elif n < target:    print("小了")
    else:
        print(f"用了 {tries} 次猜中!")
        break

项目二:学生成绩管理系统 📊

难度 ★★★ · list / dict / 函数 / 文件

项目三:通讯录系统 📞

难度 ★★★★ · 函数 / 字典 / 文件 / 异常

项目四:文本统计工具 📝

难度 ★★★ · 字符串 / 字典 / Counter

项目五:天气数据查询 🌤️

难度 ★★★★ · requests / JSON / API

项目六:数据分析项目 📈

难度 ★★★★ · Pandas / Matplotlib / 数据清洗

项目七:网络爬虫 🕷️

难度 ★★★★★ · requests / BeautifulSoup / re / CSV

项目八:AI 应用 🤖

难度 ★★★★ · API / AI 模型 / 文本处理

Python 速查手册

写代码时随手翻一翻 —— 比每次去搜更快。

35 个关键字

FalseNoneTrueandasassertasyncawaitbreakclasscontinuedefdelelifelseexceptfinallyforfromglobalifimportinislambdanonlocalnotorpassraisereturntrywhilewithyieldmatchcase

数据结构选择速查

需求推荐
可变序列list(最常用)
不可变序列tuple
去重set
键值映射dict
先进先出队列collections.deque
带默认值的字典collections.defaultdict
计数器collections.Counter
数值数组numpy.array(数据科学)
表格数据pandas.DataFrame(数据分析)

常用代码模板

Pythontemplate.py
# 1) 读文本
from pathlib import Path
text = Path("a.txt").read_text(encoding="utf-8")

# 2) 计时
import time
t0 = time.time()
# ...
print(f"{time.time() - t0:.2f}s")

# 3) 安全除法
def safe_div(a, b):
    return a / b if b != 0 else None

# 4) 链式比较 + 三元
status = "teen" if 13 <= age <= 19 else "adult"

# 5) 列表按字段排序
sorted(students, key=lambda s: s["score"], reverse=True)

# 6) 字典分组
from itertools import groupby
sorted(data, key=lambda x: x["class"])
@media print{ #topnav,#progress,.back-top{display:none!important} .hero{padding:20px 0!important;background:none!important;color:#000!important} .hero h1{color:#000!important} .hero .sub,.hero .hero-chips{color:#333!important} section{break-inside:avoid;box-shadow:none!important;border:1px solid #ccc!important} pre{background:#f5f5f5!important;color:#000!important} }