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

ค่า Boolean (True/False) ใน Python

ค่าความจริง (Truth value) ของนิพจน์ใน Python จะถูกเก็บในชนิดข้อมูล bool ซึ่งมีเพียง 2 ค่า คือ True และ False

ชนิดข้อมูล Boolean

print(True)
print(type(True))
print(False)
print(type(False))

ผลลัพธ์

True

False

นิพจน์ Boolean (Boolean Expression)

นิพจน์ที่ให้ผลลัพธ์เป็น True/False มักเกี่ยวข้องกับออเปอเรเตอร์เปรียบเทียบ (==, !=, >, <, >=, <=) ฟังก์ชัน bool() ใช้แปลงค่าให้เป็น Boolean

ไวยากรณ์

bool([x])
# คืนค่า True ถ้า x ประเมินเป็น True, มิฉะนั้น False
# ไม่มีพารามิเตอร์ คืนค่า False

ตัวอย่างการใช้ bool()

# True values
print(bool(True))           # True
print(bool(1))              # True
print(bool(1.0))            # True
print(bool('Tutorialspoint')) # True (non-empty string)

# False values
print(bool(False))          # False
print(bool(0))              # False
print(bool(0.0))            # False
print(bool(None))           # False
print(bool(()))             # False (empty tuple)
print(bool({}))             # False (empty dict)
print(bool([]))             # False (empty list)

# Comparison
a, b = 5, 10
print(bool(a == b))         # False

ผลลัพธ์

True
False
False
True
False
False
False
False
True

กฎทั่วไป (Truthy/Falsy): ใน Python ค่าต่อไปนี้ถือว่า False: None, False, 0, 0.0, '', (), [], {}, set() ส่วนที่เหลือถือว่า True