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

Ternary Operator ใน Python: If-Else แบบบรรทัดเดียว

Ternary Operator (Conditional Expression) ใน Python เขียนได้ในบรรทัดเดียว คืนค่าตามเงื่อนไข

Syntax

value_if_true if condition else value_if_false

ตัวอย่างเปรียบเทียบ

# แบบ if-else ปกติ
x, y = 5, 6
if x > y:
    print("x")
else:
    print("y")
# y

# แบบ Ternary
print("x" if x > y else "y")  # y

ใน Function

>> def find_max(a, b):
...     return a if a > b else b
...
>>> find_max(5, 6)
6

วิธีการ Implement อื่นๆ

1. Tuple Indexing

>> a, b = 0.5, 0.8
>>> (b, a)[a > b]  # False=0 → b, True=1 → a
0.8

# ป้องกันสับสนด้วย f-string
>>> (f"b:{b}", f"a:{a}")[a > b]
'b:0.8'

2. Dictionary

>> {False: f"b:{b}", True: f"a:{a}"}[a > b]
'a:0.8089...'

# สลับ key ได้
>>> {True: f"a:{a}", False: f"b:{b}"}[a > b]
'a:0.8089...'

3. Lambda (Lazy Evaluation)

>> (lambda: f"a:{a}", lambda: f"b:{b}")[a > b]()
'b:0.678...'
# เรียก function ที่เลือกเท่านั้น

Nested Ternary (Chaining)

>> from random import random
>>> x = random()
>>> result = ("Less than zero" if x < 0 else
...           "Between 0 and 5" if 0 <= x <= 5 else
...           "Greater than five")
>>> print(result)
'Between 0 and 5'
>>> x
0.08009251123993566

ข้อควรระวัง

  • อ่านยากถ้า nested ลึกเกินไป → ใช้ if-else ปกติ
  • Tuple/Dict/Lambda ways evaluate ทุก branch (ไม่ได้ lazy) เว้นแต่ lambda
  • Python ไม่มี condition ? true : false เหมือน C/Java

Best Practice: ใช้ x if cond else y สำหรับกรณีง่าย 1-2 ระดับ ส่วนซับซ้อนให้ใช้ if-else block