Python 关键字是保留字。Python 解释器使用关键字来理解程序。关键字定义了程序的结构。我们不能使用关键字来命名程序实体,例如变量、类和函数。
❓Python 中有多少个关键字?
Python 有很多关键字。随着 Python 新功能的不断涌现,关键字的数量还在持续增长。
35
个关键字
3.13
Python 版本
4
个软关键字
截至撰写本教程时,Python 3.13.12 是当前稳定版本,共有 35 个关键字。
我们可以使用 Python 解释器的帮助工具获取完整的关键字列表:
Shell
C:\Users\43898> python
Python 3.13.12 (tags/v3.13.12:1cbe481, Feb 3 2026, 18:22:25) [MSC v.1944 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>help()
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
help>
📋Python 关键字列表
我们也可以使用 keyword 模块来获取关键字列表:
Python
>>>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']
>>>len(keyword.kwlist)
35
>>>
🔸Python 软关键字
Python 3.9 引入了软关键字的概念。软关键字可以用作变量名,它们仅在特定上下文中才受到特殊处理。目前有 _、case、match 和 type 四个软关键字。
Python
>>> keyword.softkwlist
['_', 'case', 'match', 'type']
>>>
💡 为什么需要软关键字?
引入软关键字是为了避免现有代码因变量名冲突而遭到破坏。这给开发人员足够的时间对代码进行相应的修改,实现了向后兼容。
🔍如何检查字符串是否为关键字?
我们可以使用 keyword.iskeyword() 函数来检查一个字符串是否为保留关键字。
例如,print 在 Python 中是关键字吗?
Python
>>> keyword.iskeyword('print')
False
>>>
所以,print不是 Python 中的关键字。
📖Python 关键字速查表(35 个)
下表汇总了 Python 3.13 的全部 35 个关键字,包含用途说明和最小可运行示例:
| | | |
|---|
| False | | ok = False |
| None | | result = None |
| True | | done = True |
| and | | if a > 0 and b > 0: |
| as | | import math as m |
| assert | | assert x > 0 |
| async | | async def fetch(): |
| await | | data = await fetch() |
| break | | if x == 3: break |
| class | | class User: |
| continue | | if x % 2 == 0: continue |
| def | | def add(a, b): |
| del | | del nums[0] |
| elif | | elif score >= 60: |
| else | | else: print("no") |
| except | | except ValueError: |
| finally | | finally: f.close() |
| for | | for n in nums: |
| from | | from math import pi |
| global | | global count |
| if | | if age >= 18: |
| import | | import os |
| in | | if "a" in text: |
| is | | if x is None: |
| lambda | | f = lambda x: x * 2 |
| nonlocal | | nonlocal total |
| not | | if not items: |
| or | | if a == 1 or b == 1: |
| pass | | def todo(): pass |
| raise | | raise ValueError("bad") |
| return | | return a + b |
| try | | try: x = int(s) |
| while | | while n > 0: |
| with | | with open("a.txt") as f: |
| yield | | yield i |
📌总结
✦ 核心要点
Python 关键字具有特定的功能,解释器使用关键字来理解代码并执行它们。Python 目前有 35 个关键字,随着新功能的不断增加,关键字的数量还会继续增长。
🚀下一步学什么
你对 Python 关键字有了初步了解,接下来推荐继续学习以下教程,掌握 Python 编程的基础知识:
📚 推荐阅读
Python 基础教程系列
持续更新 · 欢迎关注