Python语言的关键字(Keywords)是编程语言中具有特殊含义的保留字,不能用作标识符(如变量名、函数名、类名等)。Python 3.12 版本共包含 35个 关键字,它们构成了语言语法结构的基石。掌握关键字的正确使用是编写规范、健壮 Python 程序的前提。
关键字与内置函数(如 print()、len())不同:内置函数可被重新赋值覆盖(尽管不推荐),而关键字在任何作用域内均不可被重定义,这是语言层面的硬性约束。
可通过以下方式查看当前 Python 解释器支持的所有关键字:
import keyword print(keyword.kwlist)
输出结果即为当前版本全部关键字列表。注意:不同 Python 版本关键字数量略有差异。例如 Python 3.6 引入 async 和 await,3.7 起二者成为正式关键字;3.10 引入 match、case;3.12 取消 True、False、None 的关键字身份(转为内置常量),但 True、False 仍保留为不可赋值标识符。
以下按功能模块分类详解各关键字,结合实际应用场景与易错点分析,帮助开发者建立系统性认知。
if / elif / else:条件分支for / while:循环结构break:终止当前循环continue:跳过本次循环剩余部分pass:空操作占位符and:逻辑与or:逻辑或not:逻辑非in / not in:成员测试(注意:in 是关键字,not in 是两个关键字组合)def:定义函数return:返回值lambda:匿名函数定义del:删除对象引用class:定义类self:实例引用(非关键字,但约定俗成)global / nonlocal:变量作用域声明try:异常捕获块起始except:异常处理分支finally:无论是否异常均执行块raise:主动抛出异常assert:断言检查with:上下文管理语句as:别名绑定(用于 import、with、except 等)async:定义异步函数await:等待协程执行结果True / False:布尔常量(3.12 起非关键字,但行为类似)None:空值常量is / is not:身份比较(is 是关键字,is not 是组合)import / from:模块导入yield:生成器返回值with:上下文管理(已列)match / case:结构化模式匹配(3.10+)type:类型声明(PEP 695,3.12+)if、elif、else条件语句是程序决策能力的核心。Python 的条件语句以缩进表示代码块,无需花括号,需特别注意缩进一致性。
if 表达式后必须跟布尔值或可转换为布尔值的对象(实现 __bool__() 或 __len__())elif 可重复多次,但 else 最多只能出现一次result = A if condition else B== 写成 =(赋值运算符),导致 SyntaxError示例:判断数字范围并分类
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(f"分数 {score} 对应等级:{grade}")
输出:分数 85 对应等级:B
注意:Python 没有 switch-case(3.10 前),现可用 match-case 替代。
for、while、break、continue循环结构用于重复执行代码块。
for 循环遍历可迭代对象(列表、元组、字符串、字典、集合、生成器等)while 循环在条件为真时持续执行,需手动更新条件变量,避免死循环break 终止整个当前循环;continue 跳过本次循环剩余代码,进入下一次迭代else 子句:当循环正常结束(非 break 退出)时执行示例:查找素数并使用 else 子句
for n in range(2, 15):
for x in range(2, int(n**0.5) + 1):
if n % x == 0:
print(f"{n} 可被 {x} 整除,非素数")
break
else:
print(f"{n} 是素数")
输出节选:
2 是素数
3 是素数
4 可被 2 整除,非素数
5 是素数
...
技巧:用 range(start, stop, step) 控制步长;enumerate(iterable) 同时获取索引与值。
passpass 是空操作语句,用于语法上需要语句但逻辑上无需操作的场景。
典型用途:
示例:
def placeholder_func():
pass # 待实现功能
class EmptyClass:
pass # 空类定义
try:
risky_operation()
except ValueError:
pass # 忽略 ValueError,不执行任何操作
def使用 def 定义命名函数,语法结构如下:
def 函数名(参数列表):
"""可选的文档字符串"""
函数体
return 返回值
参数类型包括:位置参数、关键字参数、可变参数(*args)、关键字可变参数(**kwargs)。
反例:错误使用可变默认参数
def append_item(item, container=[]):
container.append(item)
return container
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] —— 默认列表被复用!
正解:使用 None 占位
def append_item(item, container=None):
if container is None:
container = []
container.append(item)
return container
print(append_item(1)) # [1]
print(append_item(2)) # [2] —— 每次独立创建新列表
returnreturn 语句用于结束函数执行并返回结果。
return 或仅 return 不带表达式时,返回 None示例:返回多个值
def min_max(nums):
return min(nums), max(nums)
result = min_max([3, 1, 4, 1, 5])
print(result) # (1, 5)
mn, mx = min_max([3, 1, 4, 1, 5])
print(mn, mx) # 1 5
lambdalambda 创建小型匿名函数,语法:lambda 参数: 表达式。
sorted()、map()、filter() 等高阶函数示例:按字典值排序
data = {'apple': 3, 'banana': 1, 'cherry': 5}
sorted_items = sorted(data.items(), key=lambda x: x[1])
print(sorted_items) # [('banana', 1), ('apple', 3), ('cherry', 5)]
注意:lambda 函数不能包含注解、文档字符串或复杂逻辑,可读性差时应改用 def。
deldel 用于删除变量、列表元素、字典键等对象的引用,而非直接销毁对象。
示例:
x = [1, 2, 3]
del x[1]
print(x) # [1, 3]
y = {'a': 1, 'b': 2}
del y['b']
print(y) # {'a': 1}
注意:删除未定义变量会引发 NameError;删除不可变对象(如元组元素)会报错。
class类是面向对象编程的基础,定义方式如下:
class ClassName(BaseClass):
"""类文档字符串"""
class_attribute = 0 # 类属性
def __init__(self, value):
self.instance_attr = value # 实例属性
def method(self):
return self.instance_attr
注意:
__init__() 是构造方法,self 指代实例本身(非关键字,但强制约定)class Child(Parent1, Parent2):global、nonlocal变量作用域遵循 LEGB 规则:Local → Enclosing → Global → Built-in。
global:在局部作用域声明使用全局变量nonlocal:在嵌套函数中声明使用外层(非全局)作用域的变量示例:global 用法
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
示例:nonlocal 用法
def outer():
x = 10
def inner():
nonlocal x
x += 5
inner()
return x
print(outer()) # 15
错误用法:在 global 之前引用变量会导致 UnboundLocalError。
常用装饰器:@property、@classmethod、@staticmethod
@property:将方法转为只读属性@classmethod:类方法,第一个参数为 cls@staticmethod:静态方法,无 self 或 cls 参数示例:
class Circle:
PI = 3.14159 # 类属性
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("半径不能为负")
self._radius = value
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
@staticmethod
def is_valid_radius(r):
return r >= 0
with、aswith 语句用于自动管理资源(如文件、锁、数据库连接),确保即使发生异常也能正确释放资源。
实现原理:对象需定义 __enter__() 和 __exit__() 方法。
标准用法:
with open('data.txt', 'r') as f:
content = f.read()
# 文件自动关闭,无需手动 f.close()
自定义上下文管理器示例:
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
self.end = time.time()
print(f"耗时: {self.end - self.start:.4f} 秒")
with Timer():
sum(i for i in range(10_000_000))
输出:
耗时: 0.3821 秒
as 用于绑定上下文管理器返回值到变量名。
as在 except 子句中绑定异常对象:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"错误类型: {type(e).__name__}, 信息: {e}")
输出:
错误类型: ZeroDivisionError, 信息: division by zero
try、except、finally基本结构:
try:
# 可能出错的代码
except SpecificError as e:
# 处理特定异常
except Exception as e:
# 处理其他异常
else:
# 无异常时执行
finally:
# 无论是否异常均执行
注意:
except 子句按顺序匹配,先具体后通用except:(无异常类型)会捕获所有异常(包括 KeyboardInterrupt),慎用else 在无异常时执行,用于分离正常逻辑与异常处理示例:安全读取文件
def safe_read(filename):
try:
with open(filename, 'r') as f:
return f.read()
except FileNotFoundError:
print(f"文件 {filename} 不存在")
return None
except PermissionError:
print(f"无权限读取 {filename}")
return None
except Exception as e:
print(f"未知错误: {e}")
return None
finally:
print("操作结束")
raise使用 raise 主动触发异常:
raise ExceptionType("错误信息")raise(无参数)在 except 块中重新抛出当前异常示例:验证输入参数
def sqrt(x):
if x < 0:
raise ValueError("不能对负数开平方根")
return x ** 0.5
try:
sqrt(-1)
except ValueError as e:
print(e) # 不能对负数开平方根
assertassert condition [, message] 用于调试阶段验证假设条件。
AssertionErrorpython -O 启用优化模式禁用断言示例:验证函数前置条件
def get_item(lst, index):
assert isinstance(lst, list), "lst 必须是列表"
assert 0 <= index < len(lst), "索引越界"
return lst[index]
注意:断言不应替代正式异常处理,仅用于开发调试。
async、awaitPython 的协程(Coroutine)基于 async/await 实现,用于构建高并发 I/O 密集型应用。
核心概念:
async def:定义协程函数await:挂起当前协程,等待异步操作完成asyncio.run())执行示例:异步获取网页内容
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()
async def main():
urls = ["https://www.python.org", "https://github.com/python"]
tasks = [fetch(url) for url in urls]
results = await asyncio.gather(*tasks)
for i, content in enumerate(results):
print(f"页面 {i+1} 长度: {len(content)} 字符")
asyncio.run(main())
运行后输出:
页面 1 长度: 52147
页面 2 长度: 48321
注意:
await 只能在 async def 函数内使用await 后阻塞调用(如 time.sleep()),应使用 asyncio.sleep()import、from导入方式:
import module:导入整个模块,使用时需加前缀from module import name:导入特定对象import module as alias:指定别名from module import *:不推荐,污染命名空间最佳实践:
*)yieldyield 使函数成为生成器,返回迭代器而非单个值。
示例:斐波那契数列生成器
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fib(10):
print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34
优势:
yield from 组合子生成器match、case(3.10+)结构化模式匹配,替代复杂 if-elif 链。
基本语法:
match value:
case pattern1:
body1
case pattern2:
body2
case _:
default_body
示例:处理 HTTP 状态码
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
print(http_status(404)) # Not Found
高级用法:序列匹配、字典匹配、守卫条件
def process_command(cmd):
match cmd.split():
case ["move", x, y]:
return f"移动到 ({x}, {y})"
case ["attack", *targets]:
return f"攻击目标: {', '.join(targets)}"
case ["quit"]:
return "退出游戏"
case _:
return "无效命令"
print(process_command("attack 魔王 龙")) # 攻击目标: 魔王, 龙
Python 3.12 引入新式类型声明语法:
type Point = tuple[float, float]
type Result = str | None
def distance(p: Point) -> float:
x, y = p
return (x**2 + y**2) ** 0.5
def parse_id(id_str: str) -> Result:
return id_str if id_str.isdigit() else None
注意:type 关键字仅用于定义类型别名,与内置函数 type() 无关。