เย้ จระเข้! Condition ใน Python มีอะไรที่ "ว้าว" กว่า if-else ธรรมดา

หลายคนที่เริ่มเรียน Python มักจะรู้จักแค่

if score >= 50:
print("Pass")
else:
print("Fail")

แต่จริง ๆ แล้วระบบ Condition ของ Python มีลูกเล่นที่สวยงามและทรงพลังมาก จนบางครั้งทำให้โค้ดสั้นลงหลายเท่าตัวเมื่อเทียบกับภาษาอื่น


1. เปรียบเทียบหลายเงื่อนไขแบบ Chain ได้

ภาษาอื่นมักเขียนแบบนี้

if (age >= 18 && age <= 60)

แต่ Python เขียนได้เหมือนภาษาคณิตศาสตร์

if 18 <= age <= 60:
print("Working age")

อ่านง่ายมาก

Python จะตีความเป็น

18 <= age and age <= 60

โดยอัตโนมัติ


2. Membership Condition

ตรวจสอบว่าอยู่ในกลุ่มหรือไม่

if fruit in ["apple", "banana", "orange"]:
print("Valid fruit")

หรือ

if role not in ["admin", "staff"]:
print("Access denied")

อ่านเหมือนภาษาอังกฤษเลย


3. Truthy / Falsy

Python ไม่จำเป็นต้องเปรียบเทียบกับ True

ภาษาอื่น

if (name != "")

Python

if name:
print("Has value")

ตัวที่ถือว่าเป็น False เช่น

None
False
0
0.0
""
[]
{}
set()

ดังนั้น

items = []

if items:
print("มีข้อมูล")
else:
print("ไม่มีข้อมูล")

ไม่ต้องเขียน

if len(items) > 0:

เลย


4. Ternary Operator

เลือกค่าจากเงื่อนไขในบรรทัดเดียว

status = "Pass" if score >= 50 else "Fail"

แทน

if score >= 50:
status = "Pass"
else:
status = "Fail"

5. ใช้ Any และ All

เช็คหลายเงื่อนไขพร้อมกัน

any()

มีสักตัวเป็นจริง

scores = [10, 20, 80]

if any(score >= 50 for score in scores):
print("Someone passed")

all()

ทุกตัวต้องเป็นจริง

if all(score >= 50 for score in scores):
print("Everyone passed")

6. Assignment Expression (Walrus Operator)

ฟีเจอร์ที่หลายคนร้องว้าว

if (name := input("Name: ")):
print(f"Hello {name}")

เทียบกับแบบเดิม

name = input("Name: ")

if name:
print(f"Hello {name}")

Walrus (:=) ทำให้ Assign และ Check Condition ได้ในครั้งเดียว


7. Match-Case (Python 3.10+)

คล้าย Switch แต่เก่งกว่า

command = "start"

match command:
case "start":
print("Run")
case "stop":
print("Stop")
case _:
print("Unknown")

Match หลายค่า

match grade:
case "A" | "B":
print("Good")
case "C":
print("Average")

Match Tuple

point = (0, 1)

match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y axis {y}")
case (x, 0):
print(f"X axis {x}")

นี่คือสิ่งที่ switch ในหลายภาษาไม่สามารถทำได้


8. Guard Condition ใน Match

match age:
case x if x < 13:
print("Child")
case x if x < 20:
print("Teen")
case _:
print("Adult")

เหมือนมี if ซ้อนอยู่ใน case


9. Pattern Matching กับ Object

อันนี้หลายคนไม่รู้

@dataclass
class User:
name: str
age: int

user = User("John", 20)

match user:
case User(name, age) if age >= 18:
print(f"Adult: {name}")

Python สามารถแกะข้อมูลใน Object ออกมาตรวจสอบได้เลย


10. Dictionary Dispatch แทน if-elif ยาว ๆ

จาก

if cmd == "start":
start()
elif cmd == "stop":
stop()
elif cmd == "restart":
restart()

เปลี่ยนเป็น

actions = {
"start": start,
"stop": stop,
"restart": restart,
}

actions[cmd]()

แนวคิดนี้นิยมมากในเกมและระบบ Rule Engine


11. Condition + Iterable = พลังที่แท้จริงของ Python

สิ่งที่ทำให้ Python ต่างจากหลายภาษา คือ Condition ทำงานร่วมกับ Iterable ได้อย่างสวยงาม

users = [
{"name": "A", "active": True},
{"name": "B", "active": False},
{"name": "C", "active": True},
]

active_users = [
user
for user in users
if user["active"]
]

ผลลัพธ์

[
{'name': 'A', 'active': True},
{'name': 'C', 'active': True}
]

Condition ถูกฝังอยู่ใน List Comprehension ได้เลย


12. Condition ไม่ได้คืนแค่ True/False

หลายคนคิดว่า if รับได้แค่ Boolean

จริง ๆ Python จะเรียก

obj.__bool__()

หรือ

obj.__len__()

เบื้องหลัง

ดังนั้นเราสร้าง Condition ของตัวเองได้

class Inventory:

def __init__(self, items):
self.items = items

def __bool__(self):
return len(self.items) > 0

ใช้งาน

inv = Inventory(["Sword"])

if inv:
print("Has items")

ผลลัพธ์

Has items

Object ของเรากลายเป็น Condition ได้เอง


สิ่งที่ว้าวที่สุด

ถ้าถามว่า Condition ใน Python มีอะไรที่ภาษาอื่นไม่ค่อยมี ผมว่ามี 4 อย่างที่โดดเด่นมาก

  1. Chained Comparison
18 <= age <= 60
  1. Truthy / Falsy
if items:
  1. Pattern Matching
match value:
  1. Condition ทำงานร่วมกับ Iterable
[user for user in users if user.active]

โดยเฉพาะข้อสุดท้ายนี่คือหัวใจของ Python เลย เพราะเมื่อรวมกับ range(), zip(), enumerate(), filter(), map(), generator และ yield แล้ว คุณสามารถเขียนการกรองข้อมูลที่ซับซ้อนมาก ๆ ได้โดยแทบไม่ต้องใช้ for ซ้อนหลายชั้นเหมือนภาษาอื่นเลยครับ

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

รับติดตั้งระบบป้ายโฆษณาดิจิตอล Digital Signage ตั้งเวลาทำงานและควบคุมผ่าน Internet ได้

แจกฟรี ระบบแสดงคิวงาน สำหรับร้านนวด สปา หรือ ร้านทำผม

บริการออกแบบ Character Agent สำหรับธุรกิจ

ป้ายดิจิตอลที่โต้ตอบได้