← 返回目录

第二章:基础语法

变量、类型提示、控制流与异常

1. 变量与基本类型

Python 是动态类型语言,可通过注解增强可读性与静态检查(mypy)。

x: int = 42
name: str = "hackcha"
items: list[int] = [1, 2, 3]
empty: dict[str, float] = {}

2. 控制流

for i in range(3):
    print(i)

match status:
    case 200:
        print("ok")
    case 404:
        print("not found")
    case _:
        print("other")

match/case(Python 3.10+)适合结构化分支,类似其他语言的 switch。

3. 推导式

squares = [n * n for n in range(10) if n % 2 == 0]
unique = {c for c in "hello"}

4. 异常

try:
    1 / 0
except ZeroDivisionError as e:
    print(f"caught: {e}")
finally:
    print("cleanup")

优先捕获具体异常类型,避免裸露的 except:

📋 本章要点

掌握类型注解、match、推导式与精准异常处理,为后续 OOP 与库使用打基础。

评论加载中...