一、什么是保留关键字?
保留关键字是Python语言中具有特殊含义和功能的词汇,这些词汇构成了Python的语法基础。它们不可被重新定义或用作变量名、函数名等标识符,在代码中承担着控制程序逻辑、定义数据结构等重要职责。
二、查看保留关键字
在Python交互式命令行中执行:
python
import keyword
print(keyword.kwlist)
输出结果(Python 3.10+):
python
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
三、核心关键字详解(按功能分类)
控制结构类
- 条件控制
python
if x > 5:
print("大于5")
elif x == 5:
print("等于5")
else:
print("小于5")
- 循环控制
python
# for循环
for i in range(3):
print(i)
# while循环
count = 0
while count < 3:
print(count)
count += 1
# 循环控制
for num in [1, 2, 3, 4]:
if num % 2 == 0:
continue # 跳过偶数
if num > 3:
break # 终止循环
print(num)
逻辑运算符
python
print(True and False) # 输出False
print(True or False) # 输出True
print(not True) # 输出False
特殊值
python
result = None
is_valid = True
max_value = float('inf')
函数与类
python
def greet(name):
return f"Hello, {name}!"
class Animal:
def __init__(self, species):
self.species = species
def speak(self):
raise NotImplementedError
异常处理
python
try:
1 / 0
except ZeroDivisionError:
print("不能除以零!")
finally:
print("清理操作")
上下文管理
python
with open('data.txt') as file:
content = file.read()
# 文件自动关闭
其他重要关键字
python
# 异步编程
async def fetch_data():
await api_request()
# 占位符
def todo():
pass # 待实现
# 作用域控制
global_var = 10
def modify():
global global_var
global_var = 20
四、常见错误示例
python
# 错误:使用关键字作为变量名
class = "Computer Science" # SyntaxError
def = 10 # SyntaxError
# 错误:错误使用is
a = [1,2,3]
b = [1,2,3]
print(a is b) # False(比较对象身份)
print(a == b) # True (比较值)
五、最佳实践
-
使用IDE语法高亮功能识别关键字
-
变量命名避免使用keyword.kwlist中的词汇
-
必要时添加下划线:class_ = 'MyClass'
-
注意版本变化(如Python 3.7新增async/await)
六、进阶提示
-
yield
用于生成器函数 -
nonlocal
用于闭包中的变量修改 -
lambda
创建匿名函数 -
del
删除对象引用
掌握这些保留关键字是成为Python开发者的必经之路。建议通过实际编码练习加深理解,遇到报错时注意检查是否误用了关键字。