主题
条件分支
if、elif、else 按顺序判断,首个真值分支执行。条件可为任何对象;空序列、0、False、None 为假值。
py
def category(age: int) -> str:
if age < 0:
raise ValueError("age must be non-negative")
if age >= 18:
return "成年人"
if age >= 13:
return "青少年"
return "儿童"使用提前返回减少嵌套。比较缺失值使用 value is None,不要使用 value == None。
模式匹配
Python 3.10 起提供 match,适合匹配结构化数据或有限分支;简单布尔判断仍使用 if。
py
def http_category(status: int) -> str:
match status:
case 200 | 201 | 204:
return "success"
case 400 | 401 | 403 | 404:
return "client_error"
case _:
return "other"