Python关键字

Python 3.11 所有关键字的详细解释与示例

什么是Python关键字?

Python关键字是Python语言中预定义的、具有特殊含义的标识符。这些关键字不能用作变量名、函数名或类名等标识符。Python 3.11版本共有35个关键字,每个关键字都有其特定的用途和语法规则。

在Python中,可以通过help('keywords')命令查看所有关键字,也可以使用import keywordkeyword.kwlist来获取关键字列表。

关键字分类

控制结构关键字

用于控制程序流程和逻辑判断

if elif else for while break continue match case pass

定义和声明关键字

用于定义函数、类、变量等

def class lambda return yield import from as nonlocal global

其他关键字

用于异常处理、类型检查等

try except finally raise assert with del is in and or not True False None async await

关键字详细解释与示例

条件判断关键字:if, elif, else

用于根据条件执行不同的代码块。

python
# if-elif-else 示例
score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")

循环关键字:for, in

for用于循环遍历序列或可迭代对象,in用于检查一个值是否在序列中。

python
# for循环示例
fruits = ["苹果", "香蕉", "橙子", "葡萄"]

# 遍历列表中的元素
for fruit in fruits:
    print(fruit)

# 使用range函数生成数字序列
for i in range(5):
    print(f"第{i+1}次循环")

# 检查元素是否在列表中
if "苹果" in fruits:
    print("列表中包含苹果")

循环关键字:while

while用于根据条件重复执行代码块,直到条件变为False。

python
# while循环示例
count = 0

while count < 5:
    print(f"当前计数: {count}")
    count += 1

# 无限循环(需谨慎使用)
# while True:
#     print("这是一个无限循环")
#     break  # 用于退出无限循环

循环控制关键字:break, continue

break用于跳出当前循环,continue用于跳过当前循环的剩余部分,直接进入下一次循环。

python
# break和continue示例
for i in range(1, 11):
    if i == 5:
        print(f"找到数字5,跳出循环")
        break  # 跳出循环
    if i % 2 == 0:
        continue  # 跳过偶数,继续下一次循环
    print(f"当前数字: {i}")

函数定义关键字:def, return

def用于定义函数,return用于从函数中返回值。

python
# 函数定义与返回值示例
def greet(name):
    """向指定的人问好"""
    return f"你好,{name}!"

def add_numbers(a, b):
    """计算两个数的和"""
    result = a + b
    return result

# 调用函数
message = greet("小明")
print(message)  # 输出: 你好,小明!

sum_result = add_numbers(3, 5)
print(f"3 + 5 = {sum_result}")  # 输出: 3 + 5 = 8

类定义关键字:class

class用于定义一个类,类是面向对象编程的基本单元。

python
# 类定义示例
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def introduce(self):
        return f"我叫{self.name},今年{self.age}岁。"

# 创建类的实例
person1 = Person("张三", 25)
person2 = Person("李四", 30)

# 调用实例方法
print(person1.introduce())  # 输出: 我叫张三,今年25岁。
print(person2.introduce())  # 输出: 我叫李四,今年30岁。

异常处理关键字:try, except, finally, raise

用于捕获和处理程序运行过程中的异常。

python
# 异常处理示例
try:
    num1 = int(input("请输入第一个数字: "))
    num2 = int(input("请输入第二个数字: "))
    result = num1 / num2
    print(f"计算结果: {result}")
except ValueError:
    print("错误: 请输入有效的数字")
except ZeroDivisionError:
    print("错误: 除数不能为零")
finally:
    print("无论是否发生异常,finally块都会执行")

# 主动抛出异常
def check_age(age):
    if age < 0:
        raise ValueError("年龄不能为负数")
    return f"您的年龄是{age}岁"

try:
    check_age(-5)
except ValueError as e:
    print(f"捕获到异常: {e}")

模块导入关键字:import, from, as

用于导入模块或从模块中导入特定的函数、类或变量。

python
# 模块导入示例

# 导入整个模块
import math
print(math.sqrt(16))  # 输出: 4.0

# 从模块中导入特定函数
from random import randint, choice
print(randint(1, 100))  # 输出1-100之间的随机整数

# 使用别名导入模块
import datetime as dt
today = dt.date.today()
print(f"今天的日期是: {today}")

# 从模块中导入多个函数并使用别名
from os import path as os_path, getcwd as current_dir
print(f"当前工作目录: {current_dir()}")

上下文管理器关键字:with

with用于简化资源管理(如文件操作),确保资源在使用后被正确关闭。

python
# with语句示例

# 使用with语句操作文件
with open("example.txt", "w") as file:
    file.write("这是一个示例文本")
# 文件会在with块结束后自动关闭

# 不使用with语句需要手动关闭文件
file = open("example.txt", "r")
try:
    content = file.read()
    print(content)
finally:
    file.close()  # 需要手动关闭文件

匿名函数关键字:lambda

lambda用于创建匿名函数(即没有名称的函数)。

python
# lambda函数示例

# 基本的lambda函数
add = lambda x, y: x + y
print(add(3, 5))  # 输出: 8

# 在排序中使用lambda
students = [
    {"name": "张三", "score": 85},
    {"name": "李四", "score": 92},
    {"name": "王五", "score": 78}
]

# 按分数排序
students_sorted = sorted(students, key=lambda student: student["score"], reverse=True)
print(students_sorted)

# 在列表推导式中使用lambda
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # 输出: [1, 4, 9, 16, 25]

模式匹配关键字:match, case

match和case用于模式匹配,这是Python 3.10及以上版本新增的功能。

python
# 模式匹配示例(Python 3.10+)
def handle_request(method):
    match method.upper():
        case "GET":
            return "处理GET请求"
        case "POST":
            return "处理POST请求"
        case "PUT" | "PATCH":
            return "处理更新请求"
        case "DELETE":
            return "处理删除请求"
        case _:
            return f"不支持的请求方法: {method}"

print(handle_request("GET"))  # 输出: 处理GET请求
print(handle_request("PUT"))  # 输出: 处理更新请求
print(handle_request("HEAD"))  # 输出: 不支持的请求方法: HEAD

# 匹配复杂结构
def process_data(data):
    match data:
        case [x, y]:
            return f"接收到一个包含两个元素的列表: {x}, {y}"
        case {"name": name, "age": age}:
            return f"接收到一个字典: 姓名={name}, 年龄={age}"
        case _:
            return "未知的数据类型"

print(process_data([1, 2]))  # 输出: 接收到一个包含两个元素的列表: 1, 2
print(process_data({"name": "张三", "age": 25}))  # 输出: 接收到一个字典: 姓名=张三, 年龄=25

作用域关键字:global, nonlocal

global用于在函数内部修改全局变量,nonlocal用于在嵌套函数中修改外层函数的变量。

python
# global和nonlocal示例

# global关键字示例
global_counter = 0
def increment_global():
    global global_counter  # 声明使用全局变量
    global_counter += 1
    return global_counter

print(increment_global())  # 输出: 1
print(increment_global())  # 输出: 2

# nonlocal关键字示例
def outer_function():
    outer_var = "外层函数的变量"
    
    def inner_function():
        nonlocal outer_var  # 声明使用外层函数的变量
        outer_var = "修改后的外层变量"
        print(outer_var)
    
    inner_function()
    print(outer_var)  # 外层变量已被修改

outer_function()

特殊值关键字:True, False, None

True和False表示布尔值,None表示空值或无。

python
# True, False, None示例

# 布尔值示例
is_valid = True
is_empty = False

if is_valid:
    print("条件为真")

# 比较操作返回布尔值
a = 5
b = 10
print(a < b)  # 输出: True
print(a == b)  # 输出: False

# None示例
result = None
if result is None:
    print("结果为空")

# 函数默认返回None
def do_something():
    print("执行操作")

value = do_something()
print(value)  # 输出: None

逻辑运算符关键字:and, or, not

and、or和not用于逻辑运算。

python
# 逻辑运算符示例

# and运算符:当所有条件都为真时返回真
age = 25
has_license = True

if age >= 18 and has_license:
    print("可以开车")

# or运算符:当任一条件为真时返回真
is_member = False
has_promotion = True

if is_member or has_promotion:
    print("可以享受折扣")

# not运算符:对布尔值取反
is_raining = False

if not is_raining:
    print("可以去公园")

# 短路求值
print(False and print("不会执行到这里"))  # 输出: False
print(True or print("不会执行到这里"))  # 输出: True

异步编程关键字:async, await

async和await用于异步编程,这是Python 3.5及以上版本新增的功能。

python
# 异步编程示例
import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)  # 等待指定时间
    print(what)

async def main():
    # 并发执行两个协程
    task1 = asyncio.create_task(say_after(1, "Hello"))
    task2 = asyncio.create_task(say_after(2, "World"))
    
    print("started")
    
    # 等待两个任务完成
    await task1
    await task2
    
    print("done")

# 运行异步主函数
# asyncio.run(main())
# 输出:
# started
# Hello
# World
# done

其他关键字:del, assert, pass

del用于删除对象引用,assert用于调试时断言条件是否为真,pass是一个空操作语句。

python
# del, assert, pass示例

# del关键字示例
numbers = [1, 2, 3, 4, 5]
print(numbers)  # 输出: [1, 2, 3, 4, 5]

del numbers[2]  # 删除索引为2的元素
print(numbers)  # 输出: [1, 2, 4, 5]

del numbers  # 删除整个列表变量
# print(numbers)  # 会抛出NameError异常

# assert关键字示例
def calculate_discount(price, discount):
    assert discount >= 0 and discount <= 1, "折扣必须在0到1之间"
    return price * (1 - discount)

print(calculate_discount(100, 0.2))  # 输出: 80.0
# print(calculate_discount(100, 1.5))  # 会抛出AssertionError异常

# pass关键字示例
def incomplete_function():
    pass  # 占位符,表示函数体尚未实现

class IncompleteClass:
    pass  # 占位符,表示类体尚未实现

for i in range(5):
    if i % 2 == 0:
        pass  # 占位符,表示这里将来会有代码
    else:
        print(i)  # 输出: 1, 3

如何在Python中查看关键字?

在Python解释器中,您可以通过以下几种方式查看所有关键字:

python
# 方法一:使用help命令
>>> help('keywords')

# 方法二:使用keyword模块
>>> import keyword
>>> keyword.kwlist
['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']

# 方法三:检查一个标识符是否是关键字
>>> keyword.iskeyword('if')
True
>>> keyword.iskeyword('my_variable')
False

练习题

通过以下练习来巩固对Python关键字的理解:

练习题1:关键字识别

判断以下哪些是Python关键字,哪些不是:

  • if
  • then
  • else
  • loop
  • for
  • while
  • function
  • def
  • class
  • object

练习题2:条件语句练习

编写一个程序,根据用户输入的分数(0-100),使用if-elif-else语句判断并输出对应的等级:

  • 90-100: 优秀
  • 80-89: 良好
  • 70-79: 中等
  • 60-69: 及格
  • 0-59: 不及格

练习题3:循环和控制语句

使用for循环打印1到100之间的所有奇数,并使用continue语句跳过偶数。当遇到能被10整除的数时,使用break语句提前结束循环。

练习题4:函数和类的定义

定义一个名为Calculator的类,包含以下方法:

  • add(a, b): 返回两个数的和
  • subtract(a, b): 返回两个数的差
  • multiply(a, b): 返回两个数的积
  • divide(a, b): 返回两个数的商(注意处理除数为零的情况)

练习题5:异常处理

编写一个程序,要求用户输入两个整数,然后计算它们的和。使用try-except语句来处理可能出现的异常(如用户输入的不是数字)。

练习题6:模式匹配(Python 3.10+)

使用match-case语句编写一个程序,根据用户输入的字符串执行不同的操作:

  • 如果用户输入"hello",输出"Hello, World!"
  • 如果用户输入"bye",输出"Goodbye!"
  • 如果用户输入"help",输出"How can I help you?"
  • 对于其他输入,输出"Unknown command"