Python 编程关键词列表
Python中的关键词是保留字。您不能将它们用作变量名、函数名、类名等。
以下是Python的关键词:
Python中的关键字
FALSE | await | else | import | pass
None | break | except | in | raise
TRUE | class | finally | is | return
and | continue | for | lambda | try
as | def | from | nonlocal | while
assert | del | global | not | with
async | elif | if | or | yield
关键词模块用于获取所有关键词。首先,需要学会安装关键词模块。
安装关键词模块
要安装关键词模块,使用pip命令 −
pip install keyword
获取Python中的所有关键字
导入关键字模块后,使用kwlist属性获取所有关键字。让我们看一个示例:
示例
import keyword
# Fetch all the Keywords
kwlist = keyword.kwlist
# Display the Keywords
print("Keywords = ",kwlist)
输出
Keywords = ['False', 'None', 'True', 'and', 'as', 'assert', '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中检查有效的关键字
我们将检查Python中多个值的有效和无效关键字。为此,使用iskeyword()方法进行检查−
示例
import keyword
# Create a List
myList = ["for", "amit", "val", "while"]
# Display the List
print("List = ",myList)
keyword_list = []
non_keyword_list = []
# Looping and verifying for keywords
for item in myList:
if keyword.iskeyword(item):
keyword_list.append(item)
else:
non_keyword_list.append(item)
print("\nKeywords= " + str(keyword_list))
print("Non-Keywords= " + str(non_keyword_list))
输出
List = ['for', 'amit', 'val', 'while']
Keywords= ['for', 'while']
Non-Keywords= ['amit', 'val']