布林值是什麼?
Python 中的布林(Boolean)資料型態只有兩個值:
True # 真
False # 假
比較運算會自動產生布林值
print(10 > 9) # True
print(10 == 9) # False
print(10 < 9) # False
if
條件句中會自動轉換為布林值
a = 100
b = 30
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
output:
b is not greater than a
用 bool()
函數檢查值的真假
你可以將任何東西丟給 bool()
,Python 就會告訴你這是 True
還是 False
。print(bool("Hello")) # True
print(bool(15)) # True
x = "Hello"
y = 15
print(bool(x)) # True
print(bool(y)) # True
Python 中幾乎所有有內容的值都是 True。
被視為 True 的例子 :
- 字串 : "abc"、" "(空格也算)
- 數字 : 1、-2、3.14
- 清單 : [1, 2]、["a"]
- 元組 : (1,)
- 字典 : {"a": 1}
- 集合 : {1, 2}
EX:
print(bool("abc")) # True
print(bool(123)) # True
print(bool(["one", "two"])) # True
會被視為 False
的值(需要記熟)
- 布林 : False
- 空值 : None
- 數字 : 0、0.0
- 字串 : ""(空字串)
- 清單 : [](空清單)
- 元組 : ()
- 字典 : {}
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool({})) # False
自定義物件中 __len__()
回傳 0 也會視為 False
class MyClass:
def __len__(self):
return 0
obj = MyClass()
print(bool(obj))
output :
False