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

Python Logical Operators: and, or, not – คู่มือครบถ้วน

Logical Operators ใช้รวมเงื่อนไขหลายเงื่อนไขใน Conditional Statement (if/else) คืนค่า Boolean (True/False) Python มี 3 ตัวดำเนินการตรรกะ:

Operatorคำอธิบายตัวอย่าง
andTrue ก็ต่อเมื่อ ทั้งสอง เงื่อนไขเป็น Truea and b
orTrue ก็ต่อเมื่อ อย่างน้อยหนึ่ง เงื่อนไขเป็น Truea or b
notTrue ก็ต่อเมื่อ เงื่อนไขเป็น False (กลับค่า)not a

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

1. and Operator

ตรวจสอบเงื่อนไขทั้งคู่: อายุ ≥ 16 และบัญชีสถานะดี

age = 17
good_standing = True

if (age >= 16) and (good_standing == True):
    print("This user's account can make a purchase.")
else:
    print("This user's account cannot make a purchase.")

ทั้งสอง True → ทำงานใน if block

2. or Operator

ให้ส่วนลด 5% ถ้าเป็นสมาชิก Loyalty หรือ อายุ ≥ 65

loyalty_plan = False
age = 67

if (loyalty_plan == True) or (age >= 65):
    discount = 5
else:
    discount = 0
print("Shopper discount:", discount)  # 5

อายุ 67 True → ได้ส่วนลด แม้ Loyalty จะเป็น False

3. not Operator

ให้ส่วนลดเฉพาะผู้ที่ ยังไม่เคย ใช้ส่วนลด

used_discount = True

if not (used_discount == True):
    print("This user has not used their discount.")
else:
    print("This user has used their discount.")

used_discount == True เป็น True → not True = False → รัน else block

Operator Precedence (ลำดับความสำคัญ)

ลำดับจากสูงไปต่ำ: not → and → or ใช้วงเล็บ () เพื่อกำหนดลำดับชัดเจน

Short-Circuit Evaluation

  • and: หากตัวแรก False → ไม่ประเมินตัวหลัง (เพราะ False แน่นอน)
  • or: หากตัวแรก True → ไม่ประเมินตัวหลัง (เพราะ True แน่นอน)

ช่วยเพิ่มประสิทธิภาพและป้องกัน Error (เช่น x != 0 and 10/x > 2)

สรุป

Logical Operators ควบคุม Flow ของโปรแกรมได้ยืดหยุ่น:

  • and – ต้อง True ทั้งคู่
  • or – True อย่างน้อยหนึ่ง
  • not – กลับค่า Truthiness

ใช้วงเล็บเพื่อความชัดเจน และเข้าใจ Short-Circuit เพื่อเขียนโค้ดปลอดภัย