Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Từ Khóa (Reserved Words) trong Python

Dưới đây là danh sách các từ khóa (keywords) trong Python. Đây là từ dành riêng, không thể dùng làm tên biến, hằng số, hàm, class hay định danh nào khác. Tất cả từ khóa Python chỉ chứa chữ thường.

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield
TrueFalseNone
asawaitasync
nonlocalmatchcase

Lưu ý: Danh sách trên bao gồm cả từ khóa Python 3 mới (async, await, match, case, nonlocal). Từ khóa exec, print là hàm trong Python 3.

Kiểm tra từ khóa

import keyword
print(keyword.kwlist)        # Danh sách tất cả từ khóa
print(keyword.iskeyword('for'))  # True
print(keyword.iskeyword('hello')) # False

Soft Keywords (Python 3.10+)

match, case, _ (wildcard) là soft keywords - chỉ được coi là từ khóa trong ngữ cảnh match statement, có thể dùng làm biến ở nơi khác.