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

keyword 模組用於獲取所有關鍵字。首先,學習如何安裝 keyword 模組。

安裝 keyword 模組

要安裝 keyword 模組,請使用 pip

pip install keyword

獲取 Python 中的所有關鍵字

在匯入 keyword 模組後,使用 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']

更新時間: 2022-08-11

1 千+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告