เช่นเดียวกับภาษาอื่นๆ Python ก็มีคำสงวน (reserved words) คำเหล่านี้มีความหมายพิเศษ บางครั้งอาจเป็นคำสั่ง หรือพารามิเตอร์ เราไม่สามารถใช้คีย์เวิร์ดเป็นชื่อตัวแปรได้
คีย์เวิร์ดของ Python มีดังนี้:
| คีย์เวิร์ด | ||||
|---|---|---|---|---|
| True | False | class | def | return |
| if | elif | else | try | except |
| raise | finally | for | in | is |
| not | from | import | global | lambda |
| nonlocal | pass | while | break | continue |
| and | with | as | yield | del |
| or | assert | None |
คีย์เวิร์ด True และ False
True และ False เป็นค่าความจริงใน Python ตัวดำเนินการเปรียบเทียบคืนค่า True หรือ False ตัวแปร Boolean ก็สามารถเก็บค่าเหล่านี้ได้
ตัวอย่างโค้ด
# คีย์เวิร์ด True, False print(5 < 10) # เป็น true print(15 < 10) # เป็น false
ผลลัพธ์
True False
คีย์เวิร์ด class, def, return
class ใช้กำหนดคลาสผู้ใช้ใหม่ใน Python def ใช้กำหนดฟังก์ชันผู้ใช้ และ return ใช้กลับจากฟังก์ชันและส่งค่าให้ฟังก์ชันที่เรียก
ตัวอย่างโค้ด
# คีย์เวิร์ด Class, def, return
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({},{})'.format(self.x, self.y)
p1 = Point(10, 20)
p2 = Point(5, 7)
print('Points are: ' + str(p1) + ' and ' + str(p2))
ผลลัพธ์
Points are: (10,20) and (5,7)
คีย์เวิร์ด if, elif, else
คีย์เวิร์ดทั้งสามนี้ใช้สำหรับการตัดสินใจหรือ conditional branching เมื่อเงื่อนไขของ if เป็นจริง จะเข้าบล็อก if เมื่อเป็นเท็จ จะค้นหาเงื่อนไขอื่น หากมีบล็อก elif จะตรวจสอบเงื่อนไขกับพวกมัน และสุดท้ายเมื่อเงื่อนไขทั้งหมดเป็นเท็จ จะเข้าส่วน else
ตัวอย่างโค้ด
# คีย์เวิร์ด if, elif, else
def if_elif_else(x):
if x < 0:
print('x is negative')
elif x == 0:
print('x is 0')
else:
print('x is positive')
if_elif_else(12)
if_elif_else(-9)
if_elif_else(0)
ผลลัพธ์
x is positive x is negative x is 0
คีย์เวิร์ด try, except, raise, finally
คีย์เวิร์ดเหล่านี้ใช้จัดการข้อยกเว้น (exceptions) ใน Python ในบล็อก try เราเขียนโค้ดที่อาจ raise ข้อยกเว้น และใช้บล็อก except จัดการพวกมัน บล็อก finally จะทำงานแม้จะมีข้อยกเว้นที่ไม่ได้จัดการ
ตัวอย่างโค้ด
# คีย์เวิร์ด try, except, raise, finally
def reci(x):
if x == 0:
raise ZeroDivisionError('Cannot divide by zero')
else:
return 1/x
def try_block_example(x):
result = 'Unable to determine'
try:
result = reci(x)
except ZeroDivisionError:
print('Invalid number')
finally:
print(result)
try_block_example(15)
try_block_example(0)
ผลลัพธ์
0.06666666666666667 Invalid number Unable to determine
คีย์เวิร์ด for, in, is, not
for คือ for loop ใน Python in ใช้ตรวจสอบการมีส่วนร่วมขององค์ประกอบใน container objects มีอีกสองคีย์เวิร์ดคือ is และ not is ใช้ทดสอบ identity ของออบเจ็กต์ not ใช้กลับค่าของเงื่อนไข
ตัวอย่างโค้ด
# คีย์เวิร์ด for, in, is, not
animal_list = ['Tiger', 'Dog', 'Lion', 'Peacock', 'Snake']
for animal in animal_list:
if animal is 'Peacock':
print(animal + ' is a bird')
elif animal is not 'Snake':
print(animal + ' is mammal')
ผลลัพธ์
Tiger is mammal Dog is mammal Lion is mammal Peacock is a bird
คีย์เวิร์ด from, import
import ใช้นำเข้าโมดูลเข้า namespace ปัจจุบัน from...import ใช้นำเข้า attribute เฉพาะจากโมดูล
ตัวอย่างโค้ด
# คีย์เวิร์ด from, import from math import factorial print(factorial(12))
ผลลัพธ์
479001600
คีย์เวิร์ด global
global ใช้ระบุว่าตัวแปรที่ใช้ภายในบล็อกเป็น global variable เมื่อไม่มี global keyword ตัวแปรจะทำงานแบบ read only เพื่อแก้ไขค่า ต้องใช้ global
ตัวอย่างโค้ด
# คีย์เวิร์ด global
glob_var = 50
def read_global():
print(glob_var)
def write_global1(x):
global glob_var
glob_var = x
def write_global2(x):
glob_var = x
read_global()
write_global1(100)
read_global()
write_global2(150)
read_global()
ผลลัพธ์
50 100 100
คีย์เวิร์ด lambda
lambda ใช้สร้าง anonymous function ไม่มีชื่อ คล้าย inline function ไม่มีคำสั่ง return
ตัวอย่างโค้ด
# คีย์เวิร์ด lambda
square = lambda x: x**2
for item in range(5, 10):
print(square(item))
ผลลัพธ์
25 36 49 64 81
คีย์เวิร์ด nonlocal
nonlocal ใช้ประกาศตัวแปรใน nested function ว่าไม่ได้เป็น local ของมัน ดังนั้นมันเป็น local ของ outer function แต่ไม่ใช่ inner function ใช้แก้ไขค่า nonlocal variable มิฉะนั้นจะอยู่ในโหมด read only
ตัวอย่างโค้ด
# คีย์เวิร์ด nonlocal
def outer():
x = 50
print('x from outer: ' + str(x))
def inner():
nonlocal x
x = 100
print('x from inner: ' + str(x))
inner()
print('x from outer: ' + str(x))
outer()
ผลลัพธ์
x from outer: 50 x from inner: 100 x from outer: 100
คีย์เวิร์ด pass
pass เป็นคำสั่ง null ใน Python เมื่อ pass ทำงาน ไม่มีอะไรเกิดขึ้น ใช้เป็น placeholder
ตัวอย่างโค้ด
# คีย์เวิร์ด pass
def sample_function():
pass # Not implemented now
sample_function()
ผลลัพธ์
(No Output will come)
คีย์เวิร์ด while, break, continue, and
while คือ while loop ใน Python break ใช้ออกจากลูปปัจจุบัน ควบคุมไปยังส่วนที่อยู่ใต้ลูปทันที continue ใช้ข้าม iteration ปัจจุบัน ไปยัง iteration ถัดไป and ใช้สำหรับ logical and operation เมื่อทั้งสอง operand เป็น true จะคืนค่า True
ตัวอย่างโค้ด
# คีย์เวิร์ด while, break, continue, and
i = 0
while True:
i += 1
if i >= 5 and i <= 10:
continue
elif i == 15:
break
print(i)
ผลลัพธ์
1 2 3 4 11 12 13 14
คีย์เวิร์ด with, as
with ใช้ห่อการรันชุดโค้ด ภายในเมธอดที่นิยามโดย context manager as ใช้สร้าง alias
ตัวอย่างโค้ด
# คีย์เวิร์ด with, as
with open('sampleTextFile.txt', 'r') as my_file:
print(my_file.read())
ผลลัพธ์
Test File. We can store different contents in this file ~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]
คีย์เวิร์ด yield
yield ใช้คืนค่า generator generator เป็น iterator สร้างองค์ประกอบทีละตัว
ตัวอย่างโค้ด
# คีย์เวิร์ด yield
def square_generator(x, y):
for i in range(x, y):
yield i*i
my_gen = square_generator(5, 10)
for sq in my_gen:
print(sq)
ผลลัพธ์
25 36 49 64 81
คีย์เวิร์ด del, or
del ใช้ลบ reference ของออบเจ็กต์ or ทำ logical or operation เมื่อ operand อย่างน้อยหนึ่งตัวเป็น true คำตอบจะเป็น true
ตัวอย่างโค้ด
# คีย์เวิร์ด del, or
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
index = []
for i in range(len(my_list)):
if my_list[i] == 30 or my_list[i] == 60:
index.append(i)
for item in index:
del my_list[item]
print(my_list)
ผลลัพธ์
[10, 20, 40, 50, 60, 80, 90, 100, 110]
คีย์เวิร์ด assert
assert ใช้สำหรับ debugging เมื่อต้องการตรวจสอบ internal states ใช้ assert statement เมื่อเงื่อนไขเป็นจริง ไม่คืนค่าอะไร แต่เมื่อเป็นเท็จ จะ raise AssertionError
ตัวอย่างโค้ด
# คีย์เวิร์ด assert val = 10 assert val > 100
ผลลัพธ์
AssertionError
คีย์เวิร์ด None
None เป็นค่าคงที่พิเศษใน Python หมายถึงค่า null หรือไม่มีค่า เราไม่สามารถสร้าง none objects หลายตัวได้ แต่สามารถ assign ให้ตัวแปรต่างๆ ได้
ตัวอย่างโค้ด
# คีย์เวิร์ด None
def test_function():
print('Hello')
x = test_function()
print(x)
ผลลัพธ์
Hello None