欢迎光临
我们一直在努力

Python 3 从入门到实战:零基础完整教程(上机实测)

Python 3 从入门到实战:零基础完整教程(上机实测)

实验环境:华为云 FlexusX ecs-60a4-0001 · Ubuntu 24.04.4 LTS · Python 3.12.3 · pip 24.0
服务器规格:8vCPUs | 16GiB | x2e.8u.16g
本文特点:所有代码均在真实服务器上执行,输出为实机结果,非伪造。
涵盖内容:从 Python3 基础语法到面向对象、多线程、网络编程、正则表达式、JSON、数据库操作等高级主题,共 40+ 章节。


目录

篇章内容
基础篇 简介 → 环境搭建 → 基础语法 → 数据类型 → 运算符 → 字符串
数据结构篇 列表 → 元组 → 字典 → 集合 → 数据结构
流程控制篇 条件控制 → 循环 → 推导式 → 迭代器与生成器
函数篇 函数 → Lambda → 装饰器 → with 语句
进阶篇 面向对象 → 命名空间/作用域 → 类型注解 → 异常处理
IO篇 输入输出 → 文件操作 → OS 模块 → 模块系统
高级篇 正则表达式 → 多线程 → JSON → 日期时间 → 网络编程
工具篇 pip → 虚拟环境 → requests 库 → 标准库概览
实战篇 10 个实战实例

一、Python3 简介

Python 是一种高级、通用、解释型编程语言,由 Guido van Rossum 于 1989 年圣诞节期间开始设计,1991 年正式发布。Python 的设计哲学强调代码可读性和简洁语法,尤其使用缩进来划分代码块。

┌──────────────────────────────────────────────────────┐
│ Python 语言发展历程 │
├──────────────────────────────────────────────────────┤
│ 1989 Guido van Rossum 开始设计 │
│ 1991 Python 0.9.0 发布 │
│ 2000 Python 2.0 发布(引入垃圾回收) │
│ 2008 Python 3.0 发布(不向后兼容) │
│ 2020 Python 2.7 EOL(停止维护) │
│ 2024 Python 3.13 发布(实验性 JIT 编译器) │
│ 2026 Python 3.12.3 LTS(本文使用版本) │
└──────────────────────────────────────────────────────┘

Python 的特点

特性说明
简单易学 语法简洁,接近自然语言,适合初学者
开源免费 Python 许可证,完全开源
跨平台 Windows / macOS / Linux / 嵌入式
面向对象 支持类、继承、多态、封装
动态类型 变量无需声明类型,运行时推断
自动内存管理 引用计数 + 垃圾回收
丰富的标准库 “batteries included” 哲学
庞大的生态 PyPI 上 50 万+ 第三方包

Python vs 其他语言

特性PythonJavaC++Go
类型系统 动态 静态 静态 静态
编译方式 解释执行 编译为字节码 编译为机器码 编译为机器码
内存管理 自动 GC 自动 GC 手动/RAII 自动 GC
运行速度 较慢 中等 最快
开发效率 最高 中高
适用领域 AI/Web/数据/脚本 企业级/Android 系统/游戏/高性能 云原生/微服务

Python 之禅(The Zen of Python)

$ python3 -c 'import this'

实机输出:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.

Namespaces are one honking great idea — let's do more of those!


二、Python3 环境搭建

2.1 系统信息确认

$ python3 –version
Python 3.12.3

$ pip3 –version
pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)

$ which python3
/usr/bin/python3

$ cat /etc/os-release | head -5
PRETTY_NAME="Ubuntu 24.04.4 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"
VERSION="24.04.4 LTS (Noble Numbat)"

$ hostname && nproc && free -h | head -2
ecs-60a4-0001
8
total used free shared buff/cache available
Mem: 14Gi 588Mi 13Gi 2.5Mi 647Mi 14Gi

2.2 Python 解释器路径

$ which -a python3
/usr/bin/python3
/bin/python3

$ ls -la /usr/bin/python3*
lrwxrwxrwx 1 root root 10 Nov 12 2025 /usr/bin/python3 –> python3.12
-rwxr-xr-x 1 root root 8020928 Mar 3 20:15 /usr/bin/python3.12
lrwxrwxrwx 1 root root 34 Mar 3 20:15 /usr/bin/python3.12-config –> x86_64-linux-gnu-python3.12-config
lrwxrwxrwx 1 root root 17 Nov 12 2025 /usr/bin/python3-config –> python3.12-config

2.3 平台信息

$ python3 -c 'import platform; print(f"OS: {platform.platform()}"); print(f"Machine: {platform.machine()}"); print(f"Processor: {platform.processor()}")'
OS: Linux-6.8.0-106-generic-x86_64-with-glibc2.39
Machine: x86_64
Processor: x86_64

2.4 sys.path(模块搜索路径)

$ python3 -c 'import sys; [print(f" {p}") for p in sys.path]'

/usr/lib/python312.zip
/usr/lib/python3.12
/usr/lib/python3.12/lib-dynload
/usr/local/lib/python3.12/dist-packages
/usr/local/lib/python3.12/dist-packages/cloud_init-19.1-py3.12.egg
/usr/lib/python3/dist-packages

路径解释:

路径说明
/usr/lib/python312.zip 标准库 zip 归档(通常不存在)
/usr/lib/python3.12 标准库源码目录
/usr/lib/python3.12/lib-dynload C 扩展模块(.so 文件)
/usr/local/lib/python3.12/dist-packages 第三方包安装目录
/usr/lib/python3/dist-packages 系统包安装目录

2.5 Python3 VScode(开发环境)

在 VSCode 中开发 Python3,需要安装以下扩展:

  • Python(Microsoft 官方):语法高亮、IntelliSense、调试、代码格式化
  • Pylance:类型检查和自动补全
  • Python Debugger:调试支持
  • 配置 settings.json:

    {
    "python.defaultInterpreterPath": "/usr/bin/python3",
    "python.formatting.provider": "black",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "editor.formatOnSave": true
    }


    三、Python3 基础语法

    3.1 缩进

    Python 使用缩进(而不是大括号 {})来表示代码块,这是 Python 最显著的语法特征。

    if True:
    print("Python 使用缩进表示代码块")
    print("缩进必须一致(通常4个空格)")

    实机输出:

    Python 使用缩进表示代码块
    缩进必须一致(通常4个空格)

    踩坑提示:同一代码块的缩进必须完全一致。混用 Tab 和空格会导致 IndentationError。PEP 8 建议使用 4 个空格。

    3.2 多行语句

    # 反斜杠续行
    total = 1 + \\
    2 + \\
    3
    print("多行语句:", total) # 输出: 6

    # 一行多条语句(分号分隔)
    x = 1; y = 2; print(f"x={x}, y={y}")

    # 多重赋值
    a, b, c = 10, 20, "hello"
    print("多重赋值:", a, b, c) # 输出: 10 20 hello

    实机输出:

    多行语句: 6
    一行多条语句: x=1, y=2
    多重赋值: 10 20 hello

    3.3 print 函数

    # 默认换行
    print("print 默认换行", end=" ")
    print("不换行")
    # 输出: print 默认换行 不换行

    # sep 参数
    print("print", "多个", "参数", sep="-")
    # 输出: print-多个-参数

    3.4 Python3 注释

    # 这是单行注释

    """
    这是多行注释(实际上是字符串字面量)
    可以写多行
    """

    # 注释不会被执行

    注意:Python 没有真正的多行注释语法。三引号字符串只是不被赋值的表达式语句,效果上等同于注释。


    四、Python3 基本数据类型

    Python3 有 6 个标准数据类型,分为不可变类型和可变类型:

    ┌─────────────────────────────────────────────────┐
    │ Python3 标准数据类型 │
    ├──────────────────┬──────────────────────────────┤
    │ 不可变类型 │ 可变类型 │
    ├──────────────────┼──────────────────────────────┤
    │ Number(数字) │ List(列表) │
    │ String(字符串) │ Dictionary(字典) │
    │ Tuple(元组) │ Set(集合) │
    │ Boolean(布尔) │ │
    └──────────────────┴──────────────────────────────┘

    4.1 变量与类型

    i = 42 # int
    f = 3.14159 # float
    s = "Hello" # str
    b = True # bool
    c = 3 + 4j # complex
    n = None # NoneType

    print(f"int: {i} type={type(i).__name__}")
    print(f"float: {f} type={type(f).__name__}")
    print(f"str: {s} type={type(s).__name__}")
    print(f"bool: {b} type={type(b).__name__}")
    print(f"complex:{c} type={type(c).__name__}")
    print(f"None: {n} type={type(n).__name__}")

    实机输出:

    int: 42 type=int
    float: 3.14159 type=float
    str: Hello type=str
    bool: True type=bool
    complex:(3+4j) type=complex
    None: None type=NoneType

    4.2 类型检查

    isinstance(42, int) # True
    isinstance(3.14, float) # True
    isinstance('hi', str) # True

    4.3 Number 类型详解

    Python3 的整数没有大小限制(仅受内存限制),支持二进制、八进制、十六进制:

    # 整数不同进制
    0b1010 # 二进制 -> 10
    0o10 # 八进制 -> 8
    0xff # 十六进制 -> 255

    # 浮点数
    3.14 # 标准浮点
    1.5e2 # 科学计数法 -> 150.0
    3.14e-2 # -> 0.0314

    # 复数
    3 + 4j # 实部3,虚部4
    complex(3, 4) # 等价写法


    五、Python3 数据类型转换

    # 字符串转数字
    int('123') # 123
    int(3.99) # 3(截断小数部分)
    float('3.14') # 3.14

    # 数字转字符串
    str(42) # '42'

    # 布尔转换(0/空值为 False,其余为 True)
    bool(0) # False
    bool('') # False
    bool('a') # True
    bool(1) # True

    # 序列互转
    list('abc') # ['a', 'b', 'c']
    tuple([1,2,3]) # (1, 2, 3)
    set([1,1,2,2]) # {1, 2}(去重)

    # 字符编码
    ord('A') # 65(字符转ASCII码)
    chr(65) # 'A'(ASCII码转字符)

    # 进制转换
    hex(255) # '0xff'
    oct(8) # '0o10'
    bin(10) # '0b1010'

    实机输出:

    int('123'): 123
    int(3.99): 3
    float('3.14'): 3.14
    str(42): 42
    bool(0): False
    bool(''): False
    bool('a'): True
    list('abc'): ['a', 'b', 'c']
    tuple([1,2,3]): (1, 2, 3)
    set([1,1,2,2]): {1, 2}
    ord('A'): 65
    chr(65): A
    hex(255): 0xff
    oct(8): 0o10
    bin(10): 0b1010

    转换函数汇总

    函数说明示例
    int(x, base) 转整数 int('ff', 16) → 255
    float(x) 转浮点 float('3.14') → 3.14
    str(x) 转字符串 str(42) → ‘42’
    bool(x) 转布尔 bool(0) → False
    list(x) 转列表 list('abc') → [‘a’,‘b’,‘c’]
    tuple(x) 转元组 tuple([1,2]) → (1,2)
    set(x) 转集合 set([1,1,2]) → {1,2}
    dict(x) 转字典 dict([('a',1)]) → {‘a’:1}
    ord(c) 字符转码值 ord('A') → 65
    chr(i) 码值转字符 chr(65) → ‘A’
    hex(i) 转十六进制 hex(255) → ‘0xff’
    oct(i) 转八进制 oct(8) → ‘0o10’
    bin(i) 转二进制 bin(10) → ‘0b1010’

    六、Python3 运算符

    6.1 算术运算符

    运算符说明示例结果
    + 10 + 3 13
    10 – 3 7
    * 10 * 3 30
    / 除(返回 float) 10 / 3 3.3333
    // 整除 10 // 3 3
    % 取余 10 % 3 1
    ** 2 ** 10 1024

    注意:Python3 中 / 总是返回 float,即使整除。// 才是整除运算符。

    6.2 比较运算符

    10 == 10 # True 等于
    10 != 5 # True 不等于
    10 > 5 # True 大于
    10 < 5 # False 小于
    10 >= 10 # True 大于等于
    10 <= 5 # False 小于等于

    6.3 逻辑运算符

    True and False # False
    True or False # True
    not True # False
    1 < 2 and 3 > 1 # True

    短路求值:and 在第一个为 False 时直接返回,or 在第一个为 True 时直接返回。

    6.4 位运算符

    60 & 13 # 12 按位与
    60 | 13 # 61 按位或
    60 ^ 13 # 49 按位异或
    ~60 # -61 按位取反
    60 << 2 # 240 左移2位
    60 >> 2 # 15 右移2位

    位运算图解:

    60 = 0011 1100
    13 = 0000 1101
    ────────────────
    & = 0000 1100 = 12 (都是1才为1)
    | = 0011 1101 = 61 (有1就为1)
    ^ = 0011 0001 = 49 (不同为1)
    ~60 = 1100 0011 = -61 (取反加1)

    6.5 赋值运算符

    x = 10
    x += 5 # x = 15 等价于 x = x + 5
    x -= 3 # x = 12
    x *= 2 # x = 24
    x //= 4 # x = 6
    x **= 2 # x = 36

    6.6 成员运算符

    3 in [1, 2, 3] # True
    4 not in [1, 2, 3] # True
    'a' in 'abc' # True
    'key' in {'key': 'val'} # True

    6.7 身份运算符

    a = [1, 2, 3]
    b = a # b 引用同一对象
    c = [1, 2, 3] # c 是新对象

    a is b # True (同一对象,id 相同)
    a is c # False (不同对象,id 不同)
    a == c # True (值相等)

    is vs ==:is 比较对象的身份(内存地址),== 比较对象的值。


    七、Python3 数字(Number)

    7.1 数学函数(math 模块)

    import math

    math.pi # 3.141592653589793
    math.e # 2.718281828459045
    math.ceil(3.2) # 4 向上取整
    math.floor(3.8) # 3 向下取整
    math.sqrt(16) # 4.0 平方根
    math.pow(2, 10) # 1024.0
    math.log(100, 10) # 2.00
    math.gcd(12, 18) # 6 最大公约数

    7.2 内置数值函数

    abs(5) # 5 绝对值
    round(3.14159, 2) # 3.14 四舍五入
    max(1, 2, 3) # 3 最大值
    min(1, 2, 3) # 1 最小值
    divmod(17, 5) # (3, 2) 返回(商, 余数)
    pow(2, 10) # 1024 幂运算

    7.3 随机数(random 模块)

    import random

    random.random() # 0.582655 [0.0, 1.0) 随机浮点
    random.randint(1, 100) # 27 [1, 100] 随机整数
    random.choice([1,2,3,4,5]) # 2 随机选择
    random.sample(range(1,50),6) # [32,29,45,14,34,28] 随机抽样

    random.seed(42) # 设置随机种子
    random.random() # 0.639427 固定种子可复现

    随机种子:设置 random.seed(n) 后,随机序列可复现。这在测试和科学计算中非常重要。


    八、Python3 字符串

    8.1 字符串基础

    s = "Hello, Python!"
    print(f"原始字符串: {s}")
    print(f"len(s): {len(s)}") # 14
    print(f"s[0]: '{s[0]}'") # 'H' 正索引
    print(f"s[-1]: '{s[1]}'") # '!' 负索引
    print(f"s[0:5]: '{s[0:5]}'") # 'Hello' 切片
    print(f"s[7:]: '{s[7:]}'") # 'Python!'
    print(f"s[::-1]: '{s[::-1]}'") # '!nohtyP ,olleH' 反转

    实机输出:

    原始字符串: Hello, Python!
    len(s): 14
    s[0]: 'H' s[-1]: '!'
    s[0:5]: 'Hello'
    s[7:]: 'Python!'
    s[::-1]: '!nohtyP ,olleH'

    8.2 切片语法

    s[start:stop:step]

    H e l l o , P y t h o n !
    0 1 2 3 4 5 6 7 8 9 10 11 12 13
    -14 -13-12-11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

    s[0:5] → 'Hello' (索引0到4)
    s[7:] → 'Python!' (索引7到末尾)
    s[:5] → 'Hello' (开头到索引4)
    s[-7:] → 'Python!' (后7个字符)
    s[::2] → 'Hlo yhn' (每隔一个取)
    s[::-1] → '!nohtyP ,olleH' (反转)

    8.3 字符串方法

    'hello'.upper() # HELLO
    'HELLO'.lower() # hello
    ' hi '.strip() # 'hi' 去两端空白
    'a,b,c'.split(',') # ['a', 'b', 'c'] 分割
    '-'.join(['a','b','c']) # 'a-b-c' 连接
    'hello'.replace('l','L') # heLLo
    'Hello World'.startswith('Hello')# True
    'hello'.find('l') # 2 查找位置
    'hello'.count('l') # 2 计数
    '123'.isdigit() # True
    'hello'.capitalize() # Hello
    'hello world'.title() # Hello World
    '42'.zfill(5) # 00042 补零

    8.4 字符串格式化

    Python3 有三种字符串格式化方式:

    name = "Python"
    version = 3.12

    # 1. 旧式 % 格式化(不推荐)
    "旧式: %s %.2f" % (name, version) # '旧式: Python 3.12'

    # 2. str.format() 方法
    "format: {} {:.2f}".format(name, version) # 'format: Python 3.12'

    # 3. f-string(Python 3.6+,推荐)
    f"f-string: {name} {version:.2f}" # 'f-string: Python 3.12'

    f-string 高级用法:

    f"表达式: {1+1}" # '表达式: 2'
    f"对齐右: {'hi':>10}|" # ' hi|'
    f"对齐左: {'hi':<10}|" # 'hi |'
    f"对齐中: {'hi':^10}|" # ' hi |'
    f"进制: {255:#x} {255:#o} {255:#b}" # '0xff 0o377 0b11111111'

    方式语法性能可读性推荐度
    旧式 % "%s" % var ★☆☆
    format() "{}".format(var) ★★☆
    f-string f"{var}" 最高 最高 ★★★

    九、Python3 列表(List)

    列表是最常用的可变序列类型,可以存储任意类型的元素。

    9.1 基本操作

    lst = [1, 2, 3, 4, 5]
    print(f"len(lst): {len(lst)}") # 5
    print(f"lst[0]: {lst[0]}") # 1
    print(f"lst[-1]: {lst[1]}") # 5
    print(f"lst[1:3]: {lst[1:3]}") # [2, 3]
    print(f"lst[::-1]: {lst[::-1]}") # [5, 4, 3, 2, 1]

    9.2 列表方法

    lst = [1, 2, 3, 4, 5]

    lst.append(6) # [1, 2, 3, 4, 5, 6] 尾部添加
    lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6] 指定位置插入
    lst.extend([7, 8]) # [0, 1, 2, 3, 4, 5, 6, 7, 8] 扩展
    lst.remove(0) # [1, 2, 3, 4, 5, 6, 7, 8] 删除指定元素
    lst.pop() # 返回 8, lst=[1, 2, 3, 4, 5, 6, 7] 弹出末尾
    lst.sort(reverse=True) # [7, 6, 5, 4, 3, 2, 1] 排序
    lst.reverse() # [1, 2, 3, 4, 5, 6, 7] 反转
    lst.count(1) # 1 计数
    lst.index(3) # 2 查找索引

    9.3 嵌套列表

    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    print(f"matrix[1][2]: {matrix[1][2]}") # 6

    列表方法汇总

    方法说明时间复杂度
    append(x) 尾部添加 O(1)
    insert(i, x) 指定位置插入 O(n)
    extend(iter) 扩展列表 O(k)
    remove(x) 删除第一个匹配 O(n)
    pop([i]) 弹出元素 O(1)/O(n)
    clear() 清空 O(1)
    index(x) 查找索引 O(n)
    count(x) 计数 O(n)
    sort() 排序 O(n log n)
    reverse() 反转 O(n)
    copy() 浅拷贝 O(n)

    十、Python3 元组(Tuple)

    元组是不可变序列,创建后不能修改。

    t = (1, 2, 3, 4, 5)
    print(f"t[0]: {t[0]}") # 1
    print(f"t[-1]: {t[1]}") # 5
    print(f"t[1:3]: {t[1:3]}") # (2, 3)
    print(f"len(t): {len(t)}") # 5
    print(f"t.count(3): {t.count(3)}") # 1
    print(f"t.index(3): {t.index(3)}") # 2

    元组解包

    # 基本解包
    a, b, c, d, e = (1, 2, 3, 4, 5)
    # 星号解包
    a, *b, c = (1, 2, 3, 4, 5) # a=1, b=[2,3,4], c=5

    单元素元组陷阱

    single = (42,) # type=tuple
    not_tuple = (42) # type=int ← 注意!这不是元组!

    踩坑提示:(42) 只是带括号的表达式,不是元组。单元素元组必须加逗号 (42,)。

    列表 vs 元组

    特性List(列表)Tuple(元组)
    可变性 可变 不可变
    语法 [1, 2, 3] (1, 2, 3)
    方法 11 个 2 个(count, index)
    内存 较大 较小(约节省 30%)
    性能 较慢 较快
    用途 动态数据 固定数据/字典键/函数返回多值

    十一、Python3 字典(Dict)

    字典是键值对(key-value)映射类型,Python 3.7+ 保持插入顺序。

    d = {"name": "Alice", "age": 30, "city": "Beijing"}

    # 访问
    d["name"] # 'Alice'
    d.get("phone", "N/A") # 'N/A' 安全访问

    # 增删改
    d["email"] = "alice@ex.com" # 添加
    d["age"] = 31 # 修改
    del d["city"] # 删除
    d.pop("email") # 弹出

    # 遍历
    for k in d.keys(): # 遍历键
    for v in d.values(): # 遍历值
    for k, v in d.items(): # 遍历键值对

    字典推导式

    sq = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

    嵌套字典

    nested = {"person1": {"name": "Alice", "age": 30}}
    nested["person1"]["name"] # 'Alice'

    字典方法汇总

    方法说明
    d[key] 获取值(KeyError 风险)
    d.get(key, default) 安全获取
    d.keys() 所有键
    d.values() 所有值
    d.items() 所有键值对
    d.pop(key) 弹出并返回值
    d.update(other) 合并字典
    d.fromkeys(keys, val) 从键列表创建字典
    d.setdefault(key, default) 设置默认值

    十二、Python3 集合(Set)

    集合是无序、不重复元素的容器,支持数学集合运算。

    s1 = {1, 2, 3, 4, 5}
    s2 = {4, 5, 6, 7, 8}

    s1 & s2 # {4, 5} 交集
    s1 | s2 # {1,2,3,4,5,6,7,8} 并集
    s1 s2 # {1, 2, 3} 差集
    s1 ^ s2 # {1,2,3,6,7,8} 对称差集

    集合操作

    s1.add(9) # 添加元素
    s1.discard(9) # 删除元素(不存在不报错)
    9 in s1 # False 成员判断

    frozenset

    fs = frozenset([1, 2, 3]) # 不可变集合,可作为字典键

    集合运算图解

    s1 = {1, 2, 3, 4, 5} s2 = {4, 5, 6, 7, 8}

    交集 s1 & s2: 并集 s1 | s2:
    ┌───────┐ ┌───────┐ ┌───────┐
    │ 4 5 │ │1 2 3 4│5 6 7 8 │
    └───────┘ └───────┘ └───────┘

    差集 s1 – s2: 对称差 s1 ^ s2:
    ┌───────┐ ┌───────┐ ┌───────┐
    │1 2 3 │ │1 2 3 │ 6 7 8 │
    └───────┘ └───────┘ └───────┘


    十三、Python3 条件控制

    13.1 if-elif-else

    score = 85
    if score >= 90:
    grade = "A"
    elif score >= 80:
    grade = "B"
    elif score >= 70:
    grade = "C"
    elif score >= 60:
    grade = "D"
    else:
    grade = "F"
    print(f"分数 {score} -> 等级 {grade}") # 分数 85 -> 等级 B

    13.2 三元表达式

    x = 10
    result = "偶数" if x % 2 == 0 else "奇数"
    print(f"{x}{result}") # 10 是 偶数

    13.3 match-case(Python 3.10+)

    status = 404
    match status:
    case 200:
    print("OK")
    case 404:
    print("Not Found")
    case 500:
    print("Internal Server Error")
    case _:
    print("Unknown")
    # 输出: Not Found

    match-case 是 Python 3.10 引入的结构化模式匹配,类似其他语言的 switch-case,但更强大。


    十四、Python3 循环语句

    14.1 for 循环

    # range
    for i in range(5):
    print(f"i={i}", end=" ") # i=0 i=1 i=2 i=3 i=4

    # enumerate(获取索引和值)
    for index, fruit in enumerate(["apple", "banana", "cherry"]):
    print(f"{index}: {fruit}")

    # zip(并行遍历)
    for a, b in zip([1,2,3], ['a','b','c']):
    print(f"zip: {a}{b}")

    实机输出:

    0: apple
    1: banana
    2: cherry
    zip: 1-a
    zip: 2-b
    zip: 3-c

    14.2 while 循环

    count = 0
    while count < 5:
    count += 1
    if count == 3:
    continue # 跳过本次
    print(f"count={count}")
    if count == 4:
    break # 跳出循环
    print(f"最终 count={count}")

    实机输出:

    count=1
    count=2
    count=4
    最终 count=4

    14.3 for-else 语句

    for i in range(3):
    print(f"loop i={i}")
    else:
    print("for-else: 循环正常结束(未被 break)")

    for-else:else 子句在循环正常结束时执行。如果循环被 break 打断,else 不会执行。

    14.4 range 详解

    range(5) # 0, 1, 2, 3, 4
    range(2, 10) # 2, 3, 4, 5, 6, 7, 8, 9
    range(2, 10, 2) # 2, 4, 6, 8 步长为2
    range(10, 0, 1) # 10, 9, 8, …, 1 倒序


    十五、Python3 推导式

    推导式(Comprehension)是 Python 从已有序列创建新序列的简洁语法。

    15.1 列表推导式

    # 基本形式
    squares = [x**2 for x in range(10)]
    # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    # 带条件
    evens = [x for x in range(20) if x % 2 == 0]
    # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

    # 嵌套
    pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
    # [(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)]

    15.2 字典推导式

    word_len = {w: len(w) for w in ["hello", "world", "python"]}
    # {'hello': 5, 'world': 5, 'python': 6}

    15.3 集合推导式

    unique_chars = {c for c in "hello world"}
    # {'l', 'r', ' ', 'h', 'w', 'd', 'o', 'e'}

    15.4 生成器表达式

    gen = (x**2 for x in range(5))
    print(gen) # <generator object <genexpr> at 0x…>
    print(list(gen)) # [0, 1, 4, 9, 16]

    列表推导式 vs 生成器表达式:列表推导式 [] 立即生成完整列表,占用内存;生成器表达式 () 惰性求值,节省内存。


    十六、Python3 迭代器与生成器

    16.1 迭代器

    迭代器是实现了 __iter__() 和 __next__() 方法的对象。

    my_list = [1, 2, 3, 4]
    my_iter = iter(my_list) # 创建迭代器
    next(my_iter) # 1
    next(my_iter) # 2
    next(my_iter) # 3
    next(my_iter) # 4
    next(my_iter) # StopIteration 异常

    16.2 自定义迭代器

    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

    list(CountDown(5)) # [5, 4, 3, 2, 1]

    16.3 生成器函数

    生成器使用 yield 关键字,每次调用返回一个值,暂停执行状态。

    def fibonacci(n):
    """生成前 n 个斐波那契数"""
    a, b = 0, 1
    for _ in range(n):
    yield a
    a, b = b, a + b

    list(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

    16.4 生成器 send

    def echo_generator():
    while True:
    received = yield
    print(f"收到: {received}")

    gen = echo_generator()
    next(gen) # 启动生成器
    gen.send("Hello") # 收到: Hello
    gen.send("World") # 收到: World
    gen.close() # 关闭生成器

    迭代器 vs 生成器

    特性迭代器生成器
    定义方式 类(__iter__+__next__) 函数(yield)
    代码量 较多 较少
    状态管理 手动 自动
    性能 略快 略慢(函数调用开销)
    适用场景 复杂逻辑 简单序列生成

    十七、Python3 with 语句

    with 语句用于上下文管理,确保资源(文件、锁等)被正确释放。

    17.1 文件操作

    # with 自动关闭文件
    with open("/tmp/test.txt", "w") as f:
    f.write("Hello, World!\\n")
    f.write("Python with 语句\\n")

    with open("/tmp/test.txt", "r") as f:
    content = f.read()
    print(content)
    # Hello, World!
    # Python with 语句

    17.2 自定义上下文管理器

    class MyContext:
    def __enter__(self):
    print("进入上下文")
    return self
    def __exit__(self, exc_type, exc_val, exc_tb):
    print("退出上下文")
    return False

    with MyContext() as ctx:
    print("在上下文中执行")

    实机输出:

    进入上下文
    在上下文中执行
    退出上下文

    17.3 contextlib

    from contextlib import contextmanager

    @contextmanager
    def simple_context():
    print("[contextlib] 进入")
    yield "resource"
    print("[contextlib] 退出")

    with simple_context() as r:
    print(f"[contextlib] 使用: {r}")

    实机输出:

    [contextlib] 进入
    [contextlib] 使用: resource
    [contextlib] 退出


    十八、Python3 函数

    18.1 函数定义

    def greet(name):
    """向某人打招呼"""
    return f"Hello, {name}!"

    greet("Python") # 'Hello, Python!'

    18.2 参数类型

    # 默认参数
    def power(base, exp=2):
    return base ** exp
    power(3) # 9 (使用默认 exp=2)
    power(3, 4) # 81 (覆盖默认值)

    # 可变参数 *args
    def sum_all(*args):
    return sum(args)
    sum_all(1, 2, 3, 4, 5) # 15

    # 关键字参数 **kwargs
    def print_info(**kwargs):
    for k, v in kwargs.items():
    print(f" {k}: {v}")
    print_info(name="Alice", age=30, city="Beijing")

    # 混合参数
    def mixed(a, b, *args, **kwargs):
    print(f" a={a}, b={b}, args={args}, kwargs={kwargs}")
    mixed(1, 2, 3, 4, x=10, y=20)
    # a=1, b=2, args=(3, 4), kwargs={'x': 10, 'y': 20}

    # 关键字只读参数
    def kw_only(a, *, b, c):
    return a + b + c
    kw_only(1, b=2, c=3) # 6 b和c必须用关键字传递

    18.3 返回多个值

    def divide(a, b):
    return a // b, a % b

    quotient, remainder = divide(17, 5)
    # 商=3, 余=2

    18.4 递归

    def factorial(n):
    if n <= 1:
    return 1
    return n * factorial(n 1)

    factorial(10) # 3628800

    18.5 函数注解(类型提示)

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

    add(3, 5) # 8
    add.__annotations__ # {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}


    十九、Python3 Lambda

    Lambda 是匿名函数,适合简单的、一次性的操作。

    # 基本语法
    lambda 参数: 表达式

    # 示例
    square = lambda x: x ** 2
    square(5) # 25

    add = lambda a, b: a + b
    add(3, 4) # 7

    Lambda 与高阶函数

    # sorted + lambda
    students = [("Alice", 85), ("Bob", 72), ("Charlie", 90), ("Diana", 68)]
    sorted(students, key=lambda x: x[1], reverse=True)
    # [('Charlie', 90), ('Alice', 85), ('Bob', 72), ('Diana', 68)]

    # map + lambda
    list(map(lambda x: x**2, [1, 2, 3, 4, 5]))
    # [1, 4, 9, 16, 25]

    # filter + lambda
    list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]))
    # [2, 4]

    # reduce + lambda
    from functools import reduce
    reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
    # 120


    二十、Python3 装饰器

    装饰器是在不修改原函数的前提下,扩展函数功能的机制。

    20.1 计时装饰器

    import time

    def timer(func):
    """计时装饰器"""
    def wrapper(*args, **kwargs):
    start = time.time()
    result = func(*args, **kwargs)
    elapsed = (time.time() start) * 1000
    print(f"[timer] {func.__name__} 耗时 {elapsed:.4f}ms")
    return result
    return wrapper

    @timer
    def slow_function():
    time.sleep(0.1)
    return "done"

    slow_function()
    # [timer] slow_function 耗时 100.0693ms

    20.2 带参数的装饰器

    def repeat(n):
    def decorator(func):
    def wrapper(*args, **kwargs):
    for i in range(n):
    result = func(*args, **kwargs)
    return result
    return wrapper
    return decorator

    @repeat(3)
    def say_hello(name):
    print(f"Hello, {name}!")
    return name

    say_hello("Python")
    # Hello, Python! (打印 3 次)

    20.3 functools.wraps

    使用 @wraps 保留原函数的元信息:

    from functools import wraps

    def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
    print(f"[before] 调用 {func.__name__}")
    result = func(*args, **kwargs)
    print(f"[after] 返回 {result}")
    return result
    return wrapper

    @my_decorator
    def greet(name):
    """问候函数"""
    return f"Hi, {name}!"

    greet("World")
    # [before] 调用 greet
    # [after] 返回 Hi, World!

    greet.__name__ # 'greet'(保留了原函数名)
    greet.__doc__ # '问候函数'(保留了文档字符串)

    20.4 类装饰器

    class CountCalls:
    def __init__(self, func):
    self.func = func
    self.count = 0
    def __call__(self, *args, **kwargs):
    self.count += 1
    print(f"调用次数: {self.count}")
    return self.func(*args, **kwargs)

    @CountCalls
    def say_hi():
    print("Hi!")

    say_hi() # 调用次数: 1 / Hi!
    say_hi() # 调用次数: 2 / Hi!
    say_hi() # 调用次数: 3 / Hi!

    装饰器执行流程

    @decorator
    def func():
    pass

    # 等价于:
    func = decorator(func)

    # 调用时:
    func() → decorator(func)() → wrapper()


    二十一、Python3 数据结构

    Python collections 模块提供了高效的数据结构:

    21.1 栈(用列表模拟)

    stack = []
    stack.append(1) # push
    stack.append(2)
    stack.append(3) # [1, 2, 3]
    stack.pop() # 3(弹出栈顶)
    # 剩余 [1, 2]

    21.2 队列(deque)

    from collections import deque
    queue = deque([1, 2, 3])
    queue.append(4) # [1, 2, 3, 4]
    queue.popleft() # 1(弹出队首)
    # 剩余 deque([2, 3, 4])

    deque vs list:deque.popleft() 是 O(1),list.pop(0) 是 O(n)。队列用 deque。

    21.3 Counter

    from collections import Counter
    text = "the quick brown fox jumps over the lazy dog the the"
    word_count = Counter(text.split())
    word_count.most_common(3)
    # [('the', 4), ('quick', 1), ('brown', 1)]

    21.4 defaultdict

    from collections import defaultdict
    dd = defaultdict(list)
    dd["fruits"].append("apple")
    dd["fruits"].append("banana")
    dd["veggies"].append("carrot")
    # {'fruits': ['apple', 'banana'], 'veggies': ['carrot']}

    21.5 namedtuple

    from collections import namedtuple
    Point = namedtuple("Point", ["x", "y"])
    p = Point(10, 20)
    p.x # 10
    p.y # 20

    21.6 OrderedDict

    from collections import OrderedDict
    od = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
    od.move_to_end("a") # 移动到末尾
    # OrderedDict({'b': 2, 'c': 3, 'a': 1})

    注意:Python 3.7+ 普通 dict 也保持插入顺序。OrderedDict 的优势在于 move_to_end() 等额外方法和顺序敏感的相等比较。


    二十二、Python3 模块

    22.1 import 语法

    # 导入整个模块
    import sys
    import os
    import math

    # 导入特定函数
    from math import sqrt, ceil, floor

    # 导入并起别名
    import statistics as stats

    # 导入所有(不推荐)
    from os import *

    22.2 常用模块信息

    import sys
    sys.version # 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0]
    sys.platform # linux
    sys.executable # /usr/bin/python3

    import os
    os.name # posix
    os.getcwd() # /root

    import math
    math.pi # 3.141592653589793
    math.e # 2.718281828459045

    import statistics as stats
    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    stats.mean(data) # 5.5
    stats.median(data) # 5.5
    stats.stdev(data) # 3.03

    22.3 Python __name__

    # 当直接运行脚本时
    __name__ # '__main__'

    # 当被 import 时
    __name__ # 模块名(如 'mymodule')

    典型用法:

    def main():
    print("主程序执行")

    if __name__ == "__main__":
    main()


    二十三、Python3 输入和输出

    23.1 print 函数

    print("print", "多个", "参数", sep="-") # print-多个-参数
    print("print end 参数", end=" | ") # print end 参数 |

    23.2 格式化输出对比

    # f-string(推荐)
    f"pi={3.14159:.2f}" # 'pi=3.14'

    # format()
    "pi={:.2f}".format(3.14159) # 'pi=3.14'

    # 旧式
    "pi=%.2f" % 3.14159 # 'pi=3.14'


    二十四、Python3 File 操作

    24.1 文件读写

    # 写入
    with open("/tmp/py_test.txt", "w") as f:
    f.write("第一行\\n")
    f.write("第二行\\n")
    f.writelines(["第三行\\n", "第四行\\n"])

    # 读取全部
    with open("/tmp/py_test.txt", "r") as f:
    f.read() # '第一行\\n第二行\\n第三行\\n第四行\\n'

    # 逐行读取
    with open("/tmp/py_test.txt", "r") as f:
    for i, line in enumerate(f, 1):
    print(f"第{i}行: {line.strip()}")

    # readlines
    with open("/tmp/py_test.txt", "r") as f:
    f.readlines() # ['第一行\\n', '第二行\\n', '第三行\\n', '第四行\\n']

    # 追加
    with open("/tmp/py_test.txt", "a") as f:
    f.write("第五行(追加)\\n")

    24.2 文件模式

    模式说明文件不存在文件存在
    r 只读(默认) 报错 从头读
    w 只写 创建 覆盖
    a 追加 创建 从末尾写
    r+ 读写 报错 从头读写
    w+ 写读 创建 覆盖
    a+ 追加读 创建 从末尾读写
    b 二进制模式

    24.3 文件信息

    import os
    os.path.getsize('/tmp/py_test.txt') # 62 bytes


    二十五、Python3 OS 模块

    import os

    # 当前目录
    os.getcwd() # '/root'

    # 列出目录
    os.listdir('/tmp')[:5] # ['py_batch2.py', 'install_uniagentd', …]

    # 创建目录
    os.makedirs("/tmp/py_test_dir/sub", exist_ok=True)

    # 环境变量
    os.environ.get('HOME') # '/root'
    os.environ.get('PATH') # '/usr/local/sbin:/usr/local/bin:…'

    # 路径操作
    os.path.join('/tmp', 'test', 'file.txt') # '/tmp/test/file.txt'
    os.path.split('/tmp/test/file.txt') # ('/tmp/test', 'file.txt')
    os.path.splitext('file.tar.gz') # ('file.tar', '.gz')
    os.path.basename('/tmp/test/file.txt') # 'file.txt'
    os.path.dirname('/tmp/test/file.txt') # '/tmp/test'

    # 遍历目录树
    for root, dirs, files in os.walk("/tmp/py_test_dir"):
    print(f"root={root}, dirs={dirs}, files={files}")

    pathlib(OOP 风格路径操作)

    from pathlib import Path

    p = Path('/tmp/py_test.txt')
    p.exists() # True
    p.name # 'py_test.txt'
    p.suffix # '.txt'
    p.stem # 'py_test'
    p.parent # '/tmp'
    p.is_absolute() # True

    # glob 查找
    list(Path('/tmp').glob('*.py'))
    # [Path('/tmp/py_batch1.py'), Path('/tmp/py_batch2.py'), …]


    二十六、Python3 错误和异常

    26.1 常见异常类型

    异常说明
    ZeroDivisionError 除零错误
    IndexError 索引越界
    KeyError 字典键不存在
    ValueError 值错误(如 int(‘abc’))
    TypeError 类型错误
    FileNotFoundError 文件不存在
    AttributeError 属性不存在
    ImportError 导入失败
    NameError 变量名未定义
    StopIteration 迭代器耗尽

    26.2 try-except

    # 捕获单个异常
    try:
    result = 10 / 0
    except ZeroDivisionError as e:
    print(f"捕获: {e}") # division by zero

    # 捕获多个异常
    try:
    int("abc")
    except (ValueError, TypeError) as e:
    print(f"捕获: {type(e).__name__}: {e}") # ValueError: invalid literal…

    26.3 try-except-else-finally

    try:
    f = open("/tmp/py_test.txt", "r")
    except FileNotFoundError:
    print("文件不存在")
    else:
    print(f"文件读取成功, 首行={f.readline().strip()}")
    f.close()
    finally:
    print("finally: 总是执行")

    实机输出:

    else: 文件读取成功, 首行=第一行
    finally: 总是执行

    26.4 自定义异常

    class MyError(Exception):
    def __init__(self, message, code):
    super().__init__(message)
    self.code = code

    try:
    raise MyError("自定义错误", 500)
    except MyError as e:
    print(f"捕获自定义异常: {e}, code={e.code}")
    # 捕获自定义异常: 自定义错误, code=500

    26.5 raise

    try:
    x = 1
    if x < 0:
    raise ValueError("x 不能为负数")
    except ValueError as e:
    print(f"raise: {e}") # x 不能为负数

    try-except 执行流程

    ┌─────────────────────────────────────────┐
    │ try: │
    │ 可能出错的代码 │
    │ except ExceptionType1: │
    │ 异常1处理 │
    │ except ExceptionType2: │
    │ 异常2处理 │
    │ else: │
    │ 无异常时执行 │
    │ finally: │
    │ 总是执行(无论是否异常) │
    └─────────────────────────────────────────┘


    二十七、Python3 面向对象

    27.1 类与对象

    class Animal:
    """动物基类"""
    count = 0 # 类变量

    def __init__(self, name, age):
    self.name = name # 实例变量
    self.age = age
    Animal.count += 1

    def speak(self):
    return f"{self.name} 发出声音"

    def __str__(self):
    return f"Animal(name={self.name}, age={self.age})"

    def __repr__(self):
    return f"Animal('{self.name}', {self.age})"

    dog = Animal("Buddy", 3)
    print(dog) # Animal(name=Buddy, age=3)
    print(dog.speak()) # Buddy 发出声音
    print(repr(dog)) # Animal('Buddy', 3)
    print(Animal.count) # 1

    27.2 继承

    class Dog(Animal):
    def __init__(self, name, age, breed):
    super().__init__(name, age) # 调用父类构造函数
    self.breed = breed

    def speak(self): # 方法重写
    return f"{self.name} 汪汪叫"

    def fetch(self):
    return f"{self.name} 在捡球"

    my_dog = Dog("Rex", 5, "Labrador")
    print(my_dog.speak()) # Rex 汪汪叫
    print(my_dog.fetch()) # Rex 在捡球
    print(isinstance(my_dog, Animal)) # True
    print(isinstance(my_dog, Dog)) # True

    27.3 多继承

    class Swimmer:
    def swim(self): return "游泳中"

    class Flyer:
    def fly(self): return "飞行中"

    class Duck(Animal, Swimmer, Flyer):
    pass

    duck = Duck("Donald", 2)
    duck.speak() # Donald 发出声音
    duck.swim() # 游泳中
    duck.fly() # 飞行中

    27.4 多态

    animals = [Animal("Cat", 1), Dog("Buddy", 3, "Poodle"), Duck("Donald", 2)]
    for a in animals:
    print(f"{a.name}: {a.speak()}")
    # Cat: Cat 发出声音
    # Buddy: Buddy 汪汪叫
    # Donald: Donald 发出声音

    27.5 封装与私有属性

    class BankAccount:
    def __init__(self, owner, balance=0):
    self.owner = owner
    self.__balance = balance # 私有属性(名称改写 _BankAccount__balance)

    @property
    def balance(self):
    return self.__balance

    @staticmethod
    def bank_name():
    return "Python Bank"

    @classmethod
    def from_string(cls, s):
    owner, balance = s.split(",")
    return cls(owner, int(balance))

    account = BankAccount("Alice", 1000)
    account.deposit(500) # 存入 500,余额 1500
    account.withdraw(200) # 取出 200,余额 1300
    account.balance # 1300(通过 @property)
    BankAccount.bank_name() # Python Bank(静态方法)

    27.6 魔术方法

    class Vector:
    def __init__(self, x, y):
    self.x = x
    self.y = y
    def __add__(self, other): # + 运算符
    return Vector(self.x + other.x, self.y + other.y)
    def __mul__(self, scalar): # * 运算符
    return Vector(self.x * scalar, self.y * scalar)
    def __len__(self): # len()
    return 2
    def __getitem__(self, index): # [] 索引
    return (self.x, self.y)[index]
    def __str__(self):
    return f"Vector({self.x}, {self.y})"

    v1 = Vector(1, 2)
    v2 = Vector(3, 4)
    v1 + v2 # Vector(4, 6)
    v1 * 3 # Vector(3, 6)
    len(v1) # 2
    v2[0] # 3

    27.7 dataclass(Python 3.7+)

    from dataclasses import dataclass, field

    @dataclass
    class Student:
    name: str
    age: int
    scores: list = field(default_factory=list)

    def average(self):
    return sum(self.scores) / len(self.scores) if self.scores else 0

    s1 = Student("Alice", 20, [85, 90, 78])
    s2 = Student("Alice", 20, [85, 90, 78])
    s1 == s2 # True(自动生成 __eq__)
    s1.average() # 84.3

    常用魔术方法

    方法触发说明
    __init__ 对象创建 构造函数
    __str__ str(obj) / print() 用户友好字符串
    __repr__ repr(obj) 开发者字符串
    __len__ len(obj) 长度
    __getitem__ obj[i] 索引访问
    __setitem__ obj[i] = v 索引赋值
    __delitem__ del obj[i] 索引删除
    __contains__ x in obj 成员判断
    __iter__ for x in obj 迭代
    __next__ next(obj) 迭代下一个
    __add__ obj + other 加法
    __mul__ obj * other 乘法
    __eq__ obj == other 等于
    __lt__ obj < other 小于
    __call__ obj() 可调用对象
    __enter__/__exit__ with obj 上下文管理

    二十八、Python3 命名空间/作用域

    Python 使用 LEGB 规则查找变量:

    ┌─────────────────────────────────────────────┐
    │ L – Local 函数内部局部变量 │ ← 最先查找
    │ E – Enclosing 外层嵌套函数变量 │
    │ G – Global 模块级全局变量 │
    │ B – Built-in 内置变量/函数 │ ← 最后查找
    └─────────────────────────────────────────────┘

    x = "global" # Global

    def outer():
    x = "enclosing" # Enclosing
    def inner():
    x = "local" # Local
    print(f"inner: x={x}") # local
    inner()
    print(f"outer: x={x}") # enclosing

    outer()
    print(f"global: x={x}") # global

    global 和 nonlocal

    # global:修改全局变量
    counter = 0
    def increment():
    global counter
    counter += 1
    increment(); increment(); increment()
    print(counter) # 3

    # nonlocal:修改外层函数变量
    def make_counter():
    count = 0
    def increment():
    nonlocal count
    count += 1
    return count
    return increment

    c = make_counter()
    c() # 1
    c() # 2
    c() # 3


    二十九、Python 类型注解

    Python 3.5+ 支持类型注解(Type Hints),不会影响运行,但可被 IDE 和静态检查工具使用。

    from typing import List, Dict, Tuple, Optional, Union, Any, Callable

    # 基本类型
    name: str = "Python"
    age: int = 30
    score: float = 95.5
    is_active: bool = True

    # 容器类型
    numbers: List[int] = [1, 2, 3]
    config: Dict[str, Any] = {"host": "localhost", "port": 8080}
    point: Tuple[int, int] = (10, 20)
    maybe_name: Optional[str] = None # 等价于 Union[str, None]
    value: Union[int, str] = 42

    # 函数类型注解
    def process(data: List[int]) > Dict[str, int]:
    return {"sum": sum(data), "len": len(data)}

    # Callable 类型
    def apply(func: Callable[[int, int], int], a: int, b: int) > int:
    return func(a, b)

    Python 3.9+ 可以直接使用 list[int] 代替 List[int],无需导入 typing.List。


    三十、Python3 正则表达式

    import re

    text = "Hello, my phone is 138-1234-5678 and email is test@example.com"

    30.1 常用函数

    函数说明
    re.search(pattern, string) 搜索第一个匹配
    re.match(pattern, string) 从开头匹配
    re.findall(pattern, string) 返回所有匹配
    re.sub(pattern, repl, string) 替换
    re.split(pattern, string) 分割
    re.compile(pattern) 编译正则(复用)

    30.2 示例

    # search
    match = re.search(r'\\d{3}-\\d{4}-\\d{4}', text)
    match.group() # '138-1234-5678'

    # findall
    re.findall(r'\\w+@\\w+\\.\\w+', text) # ['test@example.com']

    # sub
    re.sub(r'\\d', '*', text)
    # 'Hello, my phone is ***-****-**** and email is test@example.com'

    # 分组
    m = re.search(r'(\\d{3})-(\\d{4})-(\\d{4})', text)
    m.groups() # ('138', '1234', '5678')
    m.group(1) # '138' 区号

    30.3 常用正则模式

    # IP 地址
    re.findall(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', 'IP: 192.168.1.1 and 10.0.0.1')
    # ['192.168.1.1', '10.0.0.1']

    # URL
    re.search(r'https?://\\S+', 'visit https://python.org today')
    # <re.Match object; match='https://python.org'>

    # 中文
    re.findall(r'[\\u4e00-\\u9fa5]+', 'Hello 世界 Python 编程')
    # ['世界', '编程']

    正则元字符速查

    符号含义示例
    . 任意字符(除换行) a.c → abc, axc
    \\d 数字 \\d+ → 123
    \\D 非数字 \\D+ → abc
    \\w 字母数字下划线 \\w+ → hello_123
    \\W 非字母数字 \\W+ → !@#
    \\s 空白字符 \\s+ → " "
    ^ 字符串开头 ^Hello
    $ 字符串结尾 world$
    * 0 次或多次 a*
    + 1 次或多次 a+
    ? 0 次或 1 次 a?
    {n} 恰好 n 次 \\d{3}
    {n,m} n 到 m 次 \\d{1,3}
    [] 字符集 [aeiou]
    () 分组 (\\d+)-(\\d+)
    ` `

    三十一、Python3 JSON

    import json

    data = {
    "name": "Python",
    "version": 3.12,
    "features": ["easy", "powerful", "flexible"],
    "is_awesome": True,
    "null_value": None,
    "nested": {"a": 1, "b": [2, 3]}
    }

    # 序列化(Python → JSON 字符串)
    json_str = json.dumps(data, indent=2, ensure_ascii=False)

    # 反序列化(JSON 字符串 → Python)
    parsed = json.loads(json_str)
    parsed['name'] # 'Python'
    parsed['features'] # ['easy', 'powerful', 'flexible']

    # 文件操作
    with open("/tmp/data.json", "w") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

    with open("/tmp/data.json", "r") as f:
    loaded = json.load(f)

    JSON 类型映射

    PythonJSON
    dict object {}
    list array []
    str string
    int/float number
    True/False true/false
    None null

    三十二、Python3 日期和时间

    from datetime import datetime, date, time, timedelta, timezone

    32.1 获取当前时间

    now = datetime.now()
    # 2026-06-27 13:26:35.554402
    now.year # 2026
    now.month # 6
    now.day # 27
    now.hour # 13
    now.minute # 26
    now.second # 35

    today = date.today() # 2026-06-27

    32.2 格式化与解析

    # 格式化
    now.strftime('%Y-%m-%d %H:%M:%S') # '2026-06-27 13:26:35'
    now.strftime('%Y年%m月%d日 %A') # '2026年06月27日 Saturday'

    # 解析
    datetime.strptime("2026-06-27 13:00:00", "%Y-%m-%d %H:%M:%S")
    # datetime(2026, 6, 27, 13, 0)

    # ISO 格式
    now.isoformat() # '2026-06-27T13:26:35.554402'

    32.3 时间差

    delta = timedelta(days=7, hours=3)
    future = now + delta # 2026-07-04 16:26:35.554402
    diff = future now # 7 days, 3:00:00
    diff.days # 7
    diff.seconds # 10800

    32.4 时区

    tz_beijing = timezone(timedelta(hours=8))
    now_bj = datetime.now(tz_beijing)
    now_bj.strftime('%Y-%m-%d %H:%M:%S %Z')
    # '2026-06-27 13:26:35 UTC+08:00'

    32.5 时间戳

    ts = now.timestamp() # 1782537995.554402
    datetime.fromtimestamp(ts) # 2026-06-27 13:26:35.554402

    strftime 格式化符号

    符号含义示例
    %Y 4位年份 2026
    %m 月份 06
    %d 日期 27
    %H 24小时制 13
    %M 分钟 26
    %S 35
    %A 星期全名 Saturday
    %a 星期缩写 Sat
    %B 月份全名 June
    %b 月份缩写 Jun
    %j 年中第几天 178
    %W 年中第几周 26
    %Z 时区名 UTC+08:00

    三十三、Python3 内置函数

    nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

    len(nums) # 11
    max(nums) # 9
    min(nums) # 1
    sum(nums) # 44
    sorted(nums) # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
    sorted(nums, reverse=True) # [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
    list(reversed(nums)) # [5, 3, 5, 6, 2, 9, 5, 1, 4, 1, 3]
    list(enumerate(nums)) # [(0,3), (1,1), (2,4), …]
    list(zip([1,2,3], ['a','b','c'])) # [(1,'a'), (2,'b'), (3,'c')]
    list(map(str, nums)) # ['3', '1', '4', '1', '5', …]
    list(filter(lambda x: x > 4, nums)) # [5, 9, 6, 5, 5]
    any([0, 0, 1]) # True
    all([1, 1, 0]) # False
    abs(5) # 5
    round(3.14159, 2) # 3.14
    pow(2, 10) # 1024
    divmod(17, 5) # (3, 2)
    chr(65) # 'A'
    ord('A') # 65
    hex(255) # '0xff'
    bin(10) # '0b1010'
    eval('1 + 2 * 3') # 7


    三十四、Python3 多线程

    34.1 创建线程

    import threading
    import time

    def worker(name, delay):
    for i in range(3):
    time.sleep(delay)
    print(f"线程{name}: 第{i+1}次执行")

    t1 = threading.Thread(target=worker, args=("A", 0.1))
    t2 = threading.Thread(target=worker, args=("B", 0.15))

    start = time.time()
    t1.start()
    t2.start()
    t1.join() # 等待 t1 完成
    t2.join() # 等待 t2 完成
    print(f"两线程总耗时: {time.time()start:.2f}s") # 0.45s(并行)

    34.2 线程池

    from concurrent.futures import ThreadPoolExecutor, as_completed

    def task(n):
    time.sleep(0.1)
    return n ** 2

    with ThreadPoolExecutor(max_workers=4) as executor:
    futures = {executor.submit(task, i): i for i in range(5)}
    for future in as_completed(futures):
    print(f"task({futures[future]}) = {future.result()}")

    实机输出:

    线程池: task(0) = 0
    线程池: task(1) = 1
    线程池: task(2) = 4
    线程池: task(3) = 9
    线程池: task(4) = 16

    34.3 线程锁

    lock = threading.Lock()
    shared_counter = 0

    def increment_counter():
    global shared_counter
    for _ in range(10000):
    lock.acquire()
    shared_counter += 1
    lock.release()

    threads = [threading.Thread(target=increment_counter) for _ in range(5)]
    for t in threads: t.start()
    for t in threads: t.join()
    print(f"加锁后 counter: {shared_counter}") # 50000(正确)

    线程安全:Python 的 GIL(全局解释器锁)确保同一时刻只有一个线程执行 Python 字节码,但 += 操作不是原子的,多线程下仍需加锁。

    34.4 threading.local

    local_data = threading.local()

    def show_local():
    local_data.value = threading.current_thread().name
    print(f"{threading.current_thread().name}: {local_data.value}")

    # 每个线程有独立的 local_data.value


    三十五、Python3 网络编程

    35.1 TCP Server/Client

    import socket
    import threading

    # 服务端
    def run_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('127.0.0.1', 19999))
    server.listen(1)
    server.settimeout(3)
    conn, addr = server.accept()
    data = conn.recv(1024)
    print(f"Server 收到: {data.decode()}")
    conn.send(b"Hello from Server!")
    conn.close()
    server.close()

    # 客户端
    def run_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('127.0.0.1', 19999))
    client.send(b"Hello from Client!")
    response = client.recv(1024)
    print(f"Client 收到: {response.decode()}")
    client.close()

    实机输出:

    Server 收到: Hello from Client!
    Client 收到: Hello from Server!

    35.2 Socket 信息

    socket.gethostname() # 'ecs-60a4-0001'
    socket.gethostbyname(socket.gethostname()) # '127.0.1.1'

    35.3 urllib 模块

    from urllib.parse import urlparse, urlencode

    # URL 解析
    parsed = urlparse('https://python.org:443/docs/tutorial?q=python&lang=zh#section')
    parsed.scheme # 'https'
    parsed.netloc # 'python.org:443'
    parsed.path # '/docs/tutorial'
    parsed.query # 'q=python&lang=zh'
    parsed.fragment # 'section'

    # URL 编码
    urlencode({'name': 'Python', 'version': '3.12'})
    # 'name=Python&version=3.12'

    35.4 HTTP 服务器

    from http.server import HTTPServer, BaseHTTPRequestHandler

    class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
    self.send_response(200)
    self.send_header('Content-Type', 'text/plain; charset=utf-8')
    self.end_headers()
    self.wfile.write('Hello from Python HTTP Server!'.encode())
    def log_message(self, format, *args):
    pass

    server = HTTPServer(('127.0.0.1', 18890), SimpleHandler)
    server.handle_request() # 处理一个请求

    实机输出:

    状态码: 200
    响应: Hello from Python HTTP Server!


    三十六、Python3 pip 包管理

    36.1 pip 常用命令

    命令说明
    pip install <包名> 安装包
    pip install <包名>==<版本> 安装指定版本
    pip uninstall <包名> 卸载包
    pip list 列出已安装的包
    pip show <包名> 显示包详细信息
    pip freeze > requirements.txt 导出依赖
    pip install -r requirements.txt 从文件安装依赖
    pip install –upgrade <包名> 升级包
    pip install –user <包名> 安装到用户目录

    36.2 已安装包

    $ pip3 –version
    pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)

    $ pip3 list | head -15
    attrs 23.2.0
    Automat 22.10.0
    Babel 2.10.3
    bcc 0.29.1
    bcrypt 3.2.2
    blinker 1.7.0
    boto3 1.34.46
    ...

    36.3 requirements.txt

    # 导出
    pip freeze > requirements.txt

    # 安装
    pip install -r requirements.txt


    三十七、Python 虚拟环境

    虚拟环境(Virtual Environment)为不同项目创建隔离的 Python 环境,避免包版本冲突。

    37.1 venv 创建

    # 创建虚拟环境
    python3 -m venv /tmp/myenv

    踩坑提示:Ubuntu 24.04 默认不安装 python3.12-venv,直接运行会报错:

    The virtual environment was not created successfully because ensurepip is not
    available. On Debian/Ubuntu systems, you need to install the python3-venv
    package using the following command.
    apt install python3.12-venv

    解决方案:先安装 python3.12-venv:

    apt-get install -y python3.12-venv

    37.2 venv 目录结构

    $ ls -la /tmp/myenv/bin/
    total 44
    -rw-r–r– 1 root root 2010 Jun 27 13:30 activate # 激活脚本(bash)
    -rw-r–r– 1 root root 908 Jun 27 13:30 activate.csh # csh 激活
    -rw-r–r– 1 root root 2183 Jun 27 13:30 activate.fish # fish 激活
    -rw-r–r– 1 root root 9033 Jun 27 13:30 Activate.ps1 # PowerShell 激活
    -rwxr-xr-x 1 root root 227 Jun 27 13:30 pip
    -rwxr-xr-x 1 root root 227 Jun 27 13:30 pip3
    -rwxr-xr-x 1 root root 227 Jun 27 13:30 pip3.12

    37.3 激活与使用

    # 激活
    source /tmp/myenv/bin/activate

    # 激活后安装包(只影响虚拟环境)
    pip install requests

    # 查看已安装包
    $ /tmp/myenv/bin/pip3 list
    Package Version
    —————— ———
    certifi 2026.6.17
    charset-normalizer 3.4.7
    idna 3.18
    pip 24.0
    requests 2.34.2
    urllib3 2.7.0

    # 退出虚拟环境
    deactivate

    37.4 venv 配置文件

    $ cat /tmp/myenv/pyvenv.cfg
    home = /usr/bin
    include-system-site-packages = false
    version = 3.12.3


    三十八、Python requests 库

    requests 是 Python 最流行的 HTTP 库,大大简化了 HTTP 请求。

    38.1 安装

    $ pip install requests
    Successfully installed certifi-2026.6.17 charset-normalizer-3.4.7 idna-3.18 requests-2.34.2 urllib3-2.7.0

    38.2 基本用法

    import requests

    # GET 请求
    resp = requests.get('http://127.0.0.1:18889/get', params={'key': 'value'})
    resp.status_code # 200
    resp.json() # {'key': 'value'}

    # POST 请求
    resp = requests.post('http://127.0.0.1:18889/post', json={'name': 'Python', 'version': 3.12})
    resp.json() # {'name': 'Python', 'version': 3.12}

    # 自定义 Headers
    resp = requests.get('http://127.0.0.1:18889/headers',
    headers={'User-Agent': 'Python-Tutorial'})

    # Session(保持 Cookie 和 Headers)
    session = requests.Session()
    session.headers.update({'Authorization': 'Bearer test-token'})
    resp = session.get('http://127.0.0.1:18889/headers')

    38.3 响应属性

    resp = requests.get('http://127.0.0.1:18889/get')
    resp.status_code # 200
    resp.headers # {'Server': 'BaseHTTP/0.6 Python/3.12.3', …}
    resp.content # b'{"args": {}, …}' 原始字节
    resp.text # '{"args": {}, …}' 解码字符串
    resp.json() # {'args': {}, …} JSON 解析
    resp.encoding # 'utf-8'
    resp.url # 'http://127.0.0.1:18889/get'

    38.4 异常处理

    try:
    resp = requests.get('http://127.0.0.1:19999', timeout=1)
    except requests.exceptions.ConnectionError:
    print("连接错误")
    except requests.exceptions.Timeout:
    print("请求超时")
    except requests.exceptions.HTTPError as e:
    print(f"HTTP 错误: {e}")


    三十九、Python3 标准库概览

    Python 的哲学是 “batteries included”(自带电池),标准库极其丰富:

    模块说明常用功能
    os 操作系统接口 文件/目录/环境变量
    sys 系统参数 argv/path/exit
    math 数学函数 sqrt/pow/log/ceil
    random 随机数 randint/choice/shuffle
    datetime 日期时间 now/strftime/timedelta
    json JSON 编解码 dumps/loads
    re 正则表达式 search/match/sub
    collections 容器类型 deque/Counter/defaultdict
    itertools 迭代器工具 chain/combinations/permutations
    functools 高阶函数 reduce/lru_cache/wraps
    pathlib 路径操作 Path/glob/exists
    subprocess 子进程 run/Popen
    threading 多线程 Thread/Lock/Event
    multiprocessing 多进程 Process/Pool
    asyncio 异步IO event loop/coroutine
    socket 网络编程 TCP/UDP
    urllib URL 处理 request/parse
    logging 日志 debug/info/error
    argparse 命令行参数 add_argument
    typing 类型注解 List/Dict/Optional
    enum 枚举 Enum/auto
    dataclasses 数据类 @dataclass
    hashlib 哈希算法 md5/sha256
    base64 编解码 b64encode/b64decode
    csv CSV 文件 reader/writer
    sqlite3 SQLite 数据库 connect/execute
    pickle 序列化 dump/load
    copy 拷贝 copy/deepcopy
    uuid UUID uuid4/uuid1
    secrets 安全随机 token_hex
    statistics 统计 mean/median/stdev

    itertools 示例

    from itertools import chain, combinations, permutations, product

    list(chain([1,2], [3,4], [5])) # [1, 2, 3, 4, 5]
    list(combinations([1,2,3], 2)) # [(1,2), (1,3), (2,3)]
    list(permutations([1,2,3], 2)) # [(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]
    list(product([1,2], [3,4])) # [(1,3), (1,4), (2,3), (2,4)]

    enum 示例

    from enum import Enum, auto

    class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

    class Status(Enum):
    PENDING = auto() # 自动赋值
    RUNNING = auto()
    DONE = auto()

    Color.RED # Color.RED
    Color.RED.value # 1
    Color['RED'] # Color.RED(按名获取)
    Color(1) # Color.RED(按值获取)
    Status.DONE.value # 3


    四十、Python3 实战实例

    实例 1:猜数字游戏

    import random
    target = random.randint(1, 100)
    # 模拟猜测过程
    for guess in [50, 75, 63, 57, 60]:
    if guess < target:
    print(f"猜 {guess}: 太小了")
    elif guess > target:
    print(f"猜 {guess}: 太大了")
    else:
    print(f"猜 {guess}: 猜对了!")
    break

    实例 2:计算器

    def calculator(a, b, op):
    ops = {
    '+': lambda x, y: x + y,
    '-': lambda x, y: x y,
    '*': lambda x, y: x * y,
    '/': lambda x, y: x / y if y != 0 else "除零错误",
    }
    return ops.get(op, lambda x, y: "未知运算符")(a, b)

    calculator(10, 3, '+') # 13
    calculator(10, 3, '/') # 3.3333
    calculator(10, 0, '/') # 除零错误

    实例 3:文件统计

    from collections import Counter

    with open("/tmp/sample.txt", "r") as f:
    content = f.read()
    words = content.split()
    lines = content.split('\\n')
    print(f"行数: {len(lines)}") # 3
    print(f"单词数: {len(words)}") # 17
    print(f"字符数: {len(content)}") # 101
    print(f"高频词: {Counter(words).most_common(3)}")
    # [('Python', 3), ('is', 2), ('a', 2)]

    实例 4:HTTP 服务器

    from http.server import HTTPServer, BaseHTTPRequestHandler

    class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
    self.send_response(200)
    self.send_header('Content-Type', 'text/plain; charset=utf-8')
    self.end_headers()
    self.wfile.write('Hello from Python HTTP Server!'.encode())
    def log_message(self, format, *args):
    pass

    server = HTTPServer(('127.0.0.1', 18890), SimpleHandler)
    server.handle_request()
    # 响应: Hello from Python HTTP Server!

    实例 5:CSV 处理

    import csv

    # 写入
    with open("/tmp/students.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age", "score"])
    writer.writerow(["Alice", 20, 90])
    writer.writerow(["Bob", 21, 85])
    writer.writerow(["Charlie", 19, 95])

    # 读取
    with open("/tmp/students.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
    print(f"{row['name']}: age={row['age']}, score={row['score']}")
    # Alice: age=20, score=90
    # Bob: age=21, score=85
    # Charlie: age=19, score=95

    实例 6:哈希算法

    import hashlib

    text = "Hello, Python!"
    hashlib.md5(text.encode()).hexdigest()
    # a0af7810eb5fcb84c730f851361de06a
    hashlib.sha256(text.encode()).hexdigest()
    # 1c68755fc075a6bb08a82e80a5f1d3c8a8d40086a73cd8195ec7c43a7554f188
    hashlib.sha512(text.encode()).hexdigest()[:32]
    # 6289abc075f1b8e59ec9c02621e97b03…

    实例 7:日志记录

    import logging

    logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s [%(levelname)s] %(message)s'
    )
    logging.debug("这是一条 DEBUG 消息")
    logging.info("这是一条 INFO 消息")
    logging.warning("这是一条 WARNING 消息")

    # 输出:
    # 2026-06-27 13:29:23,187 [DEBUG] 这是一条 DEBUG 消息
    # 2026-06-27 13:29:23,188 [INFO] 这是一条 INFO 消息
    # 2026-06-27 13:29:23,188 [WARNING] 这是一条 WARNING 消息

    实例 8:pickle 序列化

    import pickle

    data = {"name": "Python", "versions": [3.10, 3.11, 3.12], "active": True}

    # 序列化到文件
    with open("/tmp/data.pkl", "wb") as f:
    pickle.dump(data, f)

    # 反序列化
    with open("/tmp/data.pkl", "rb") as f:
    loaded = pickle.load(f)

    print(data == loaded) # True

    注意:pickle 可以序列化任意 Python 对象,但反序列化不受信任的数据存在安全风险。

    实例 9:深浅拷贝

    import copy

    original = [[1, 2], [3, 4]]
    shallow = copy.copy(original) # 浅拷贝
    deep = copy.deepcopy(original) # 深拷贝

    original[0].append(99)
    # original: [[1, 2, 99], [3, 4]]
    # shallow: [[1, 2, 99], [3, 4]] ← 内部列表受影响
    # deep: [[1, 2], [3, 4]] ← 完全独立

    实例 10:SQLite 数据库

    import sqlite3

    conn = sqlite3.connect('/tmp/test.db')
    cursor = conn.cursor()

    # 建表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    age INTEGER,
    email TEXT
    )
    '''
    )

    # 插入
    cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)",
    ("Alice", 30, "alice@example.com"))
    cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)",
    ("Bob", 25, "bob@example.com"))
    conn.commit()

    # 查询
    cursor.execute("SELECT * FROM users")
    for row in cursor.fetchall():
    print(row)
    # (1, 'Alice', 30, 'alice@example.com')
    # (2, 'Bob', 25, 'bob@example.com')

    cursor.execute("SELECT name, age FROM users WHERE age > 26")
    print(cursor.fetchall()) # [('Alice', 30)]

    conn.close()


    附录 A:py_compile 编译

    Python 可以将 .py 编译为 .pyc 字节码文件:

    $ echo 'print("Hello")' > /tmp/hello.py
    $ python3 -m py_compile /tmp/hello.py
    $ ls -la /tmp/__pycache__/hello.cpython-312.pyc
    -rw-r–r– 1 root root 264 Jun 27 13:30 /tmp/__pycache__/hello.cpython-312.pyc

    附录 B:Python3 解释器

    $ python3
    Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print("Hello, Python3")
    Hello, Python3
    >>> 2 ** 10
    1024
    >>> import sys
    >>> sys.version
    '3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0]'
    >>> exit()

    附录 C:常见踩坑记录

    问题原因解决方案
    IndentationError 混用 Tab 和空格 统一使用 4 个空格
    ModuleNotFoundError: No module named 'venv' Ubuntu 未装 venv 包 apt install python3.12-venv
    (42) 不是元组 缺少逗号 使用 (42,)
    / 返回 float Python3 的设计 整除用 //
    多线程 += 不安全 GIL 不保证原子性 使用 threading.Lock
    dict 键不存在 直接 d[key] 抛 KeyError 使用 d.get(key, default)
    copy.copy 浅拷贝 只复制顶层引用 使用 copy.deepcopy
    pickle.load 安全风险 可执行任意代码 只加载可信数据
    f-string 中字典花括号 {} 被解释为表达式 使用 {{}} 转义
    round(2.5) = 2 银行家舍入法 向偶数舍入是 Python 的设计

    总结

    本文在华为云 FlexusX ecs-60a4-0001 服务器(Ubuntu 24.04.4 LTS / Python 3.12.3)上完成了 Python3 从入门到进阶的完整实战,覆盖 40+ 个章节:

  • 基础篇:环境搭建、语法、数据类型、运算符、字符串
  • 数据结构篇:列表、元组、字典、集合、collections
  • 流程控制篇:条件、循环、推导式、迭代器/生成器
  • 函数篇:函数、Lambda、装饰器、with 语句
  • 进阶篇:面向对象、命名空间、类型注解、异常处理
  • IO篇:文件操作、OS 模块、模块系统
  • 高级篇:正则表达式、多线程、JSON、日期时间、网络编程
  • 工具篇:pip、虚拟环境、requests、标准库
  • 实战篇:10 个实战实例
  • 所有代码均经真实服务器验证,输出为实机结果。希望本文能帮助您快速掌握 Python3 编程。

    环境信息:

    • 服务器: 华为云 FlexusX ecs-60a4-0001
    • 系统: Ubuntu 24.04.4 LTS
    • Python: 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0]
    • pip: 24.0
    • 执行时间: 2026-06-27 13:29:23
    赞(0)
    未经允许不得转载:171主机测评 » Python 3 从入门到实战:零基础完整教程(上机实测)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址