Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

รายการ Keywords ในภาษา Python Programming

โมดูล keyword ในไลบรารีมาตรฐานของ Python ช่วยตรวจสอบว่าสตริงใดเป็น keyword ของภาษา Python

ฟังก์ชันหลัก

  • keyword.iskeyword(s): คืนค่า True ถ้า s เป็น keyword ของ Python
  • keyword.kwlist: คืนค่า sequence ของ keywords ทั้งหมดที่ interpreter กำหนด (รวม keywords ที่จะเพิ่มในอนาคต)

ตัวอย่างการใช้งาน


>>> import keyword
>>> kwlist = keyword.kwlist
>>> 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']

>>> kw = input('enter a keyword..')
enter a keyword..catch
>>> kw in kwlist
False

>>> kw = input('enter a keyword..')
enter a keyword..import
>>> kw in kwlist
True

รายการ Keywords ทั้งหมด (Python 3.7+)

Keywordคำอธิบาย
False, None, Trueค่าคงที่ในตัว (singletons)
and, or, notBoolean operators
asAlias ใน import/exception handling
assertDebugging assertion
async, awaitAsynchronous programming
break, continueควบคุม Loop
classสร้าง Class
defสร้าง Function
delลบ Object/Attribute
elif, elseConditional branching
except, finally, tryException handling
for, whileLoop statements
from, importModule import
global, nonlocalVariable scope
inMembership test / Loop iteration
isIdentity test
lambdaAnonymous function
passNull statement
raiseRaise exception
returnReturn from function
withContext manager
yieldGenerator function

ข้อควรทราบ

  • Keywords เป็นคำสงวน ไม่สามารถใช้เป็นชื่อตัวแปร ฟังก์ชัน คลาส โมดูล ได้
  • รายการอาจเพิ่มขึ้นในเวอร์ชันใหม่ (เช่น async, await เพิ่มใน Python 3.5)
  • ใช้ keyword.iskeyword() ตรวจสอบก่อนตั้งชื่อได้
  • Soft keywords (Python 3.10+): match, case, _ (ใช้ใน pattern matching)