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

Short-Circuit Evaluation ใน Python (เทคนิคการประเมินแบบลัดวงจร)

ข้อผิดพลาดทั่วไปของมือใหม่คือเข้าใจผิดการทำงานของ Boolean Operators (and, or) ซึ่งมาจากวิธีที่ Python Interpreter อ่านนิพจน์เหล่านี้

ตัวอย่างที่ทำให้สับสน

>>> 'x' == ('x' or 'y')
True
>>> 'y' == ('x' or 'y')
False
>>> 'x' == ('x' and 'y')
False
>>> 'y' == ('x' and 'y')
True

ดูเหมือน and/or ชำรุด แต่จริงๆ แล้ว Interpreter ทำงานถูกต้องแค่ไม่ใช่สิ่งที่เราคิด

หลักการ Short-Circuit Evaluation

สำหรับ OR Expression

  1. ตรวจสอบ Statement แรก หากเป็น True → คืนค่าของ Statement แรก ทันที (ไม่ดู Statement ที่สอง)
  2. หาก Statement แรกเป็น False → ตรวจสอบและคืนค่า Statement ที่สอง

เพราะ OR Expression จะเป็น True หากมีอย่างน้อยหนึ่งค่าเป็น True

สำหรับ AND Expression

  1. ตรวจสอบ Statement แรก หากเป็น False → คืนค่าของ Statement แรก ทันที (ไม่ดู Statement ที่สอง)
  2. หาก Statement แรกเป็น True → ตรวจสอบและคืนค่า Statement ที่สอง

เพราะ AND Expression จะเป็น True ก็ต่อเมื่อทั้งคู่เป็น True

การวิเคราะห์กรณีตัวอย่าง

กรณี 1: 'x' == ('x' or 'y')

# 1. ประเมิน ('x' or 'y') ก่อน
# 2. 'x' เป็น non-empty string → True → คืน 'x'
# 3. เปรียบเทียบ 'x' == 'x' → True

กรณี 2: 'y' == ('x' or 'y')

# 1. ประเมิน ('x' or 'y') → คืน 'x' (เพราะ 'x' เป็น True)
# 2. เปรียบเทียบ 'y' == 'x' → False

กรณี 3: 'x' == ('x' and 'y')

# 1. ประเมิน ('x' and 'y')
# 2. 'x' เป็น True → ตรวจสอบ 'y' → 'y' เป็น True → คืน 'y'
# 3. เปรียบเทียบ 'x' == 'y' → False

กรณี 4: 'y' == ('x' and 'y')

# 1. ประเมิน ('x' and 'y') → คืน 'y'
# 2. เปรียบเทียบ 'y' == 'y' → True

ตารางสรุปจากเอกสารทางการ

OperationResultคำอธิบาย
x or yIf x is false, then y, else xประเมิน y ก็ต่อเมื่อ x เป็น False
x and yIf x is false, then x, else yประเมิน y ก็ต่อเมื่อ x เป็น True
not xIf x is false, then True, else FalseNot มี Priority ต่ำกว่า Non-Boolean Operators

การประยุกต์ใช้งานจริง

# Default Value Pattern
value = user_input or "default"

# Safe Navigation
result = obj and obj.method()

# Conditional Execution
is_valid and process_data()

# Short-circuit ใน List Comprehension
first_even = next((x for x in numbers if x % 2 == 0), None)