Python bool 布林值:True 與 False 邏輯基礎

Python 的 bool 布林值只有兩個值:True(真)與 False(假),是所有條件判斷與控制流程的基礎。本文完整說明 bool 的定義、大小寫規定、真值測試(Truthy / Falsy)、比較運算子與邏輯運算子如何回傳布林值,以及在 ifwhile 與量化策略訊號判斷中的實際應用,幫助你建立穩固的邏輯思維基礎。

Cinematic dark alchemy forge with two glowing orbs suspended in mid-air, one blazing white labeled TRUE and one deep void black labeled FALSE, ancient rune scales balancing light and shadow, golden energy beams connecting the orbs to branching decision pathways carved in stone, deep dramatic shadows, cinematic lighting, 16:9

什麼是 Python 布林值?

布林值(bool)是 Python 中最簡單的資料型別,只有兩個可能的值:TrueFalse。它的名稱來自數學家 George Boole,用來表示邏輯上的「是」與「否」。在 Python 中,bool 是 int 的子類別,True 的數值等於 1False 的數值等於 0,這使得布林值可以直接參與數學運算。

可以把布林值想像成煉金坊裡的開關閥門True 代表閥門開啟,熔爐內的反應(程式碼區塊)才會執行;False 代表閥門關閉,整段反應被跳過。程式的每一個 if 判斷、每一個 while 迴圈,最終都是在問一個問題:「這個閥門是開的嗎?」

核心語法:True 與 False

# === 基本布林值宣告 ===
is_open    = True     # 大寫 T,不可寫成 true
is_closed  = False    # 大寫 F,不可寫成 false

print(type(is_open))   # 
print(type(is_closed)) # 

# bool 是 int 的子類別:True = 1、False = 0
print(True  + 1)   # 2
print(False + 5)   # 5
print(True  * 10)  # 10
print(False * 10)  # 0

# === 比較運算子回傳 bool ===
price = 185.5

print(price > 180)    # True(價格高於 180)
print(price < 180)    # False
print(price == 185.5) # True(相等,雙等號)
print(price != 185.5) # False(不等於)
print(price >= 185.5) # True(大於等於)
print(price <= 185.0) # False(小於等於)
Python 的 == 是「比較是否相等」,= 是「賦值」,兩者意義完全不同。初學者最容易在 if 條件裡誤用 =,導致語法錯誤(SyntaxError)。記住:比較用雙等號 ==
# === 邏輯運算子組合 bool ===
rsi   = 25
price = 183.0

# and:兩個條件都為 True,結果才為 True
buy_signal = (rsi < 30) and (price > 180)
print(buy_signal)   # True(RSI 超賣 且 價格高於門檻)

# or:至少一個條件為 True,結果就為 True
alert = (rsi < 20) or (price > 190)
print(alert)        # False(兩個條件都不成立)

# not:反轉布林值
in_position = False
print(not in_position)   # True(目前沒有持倉,所以可以開倉)

# 組合使用:多條件策略訊號
fast_ma    = 186.2
slow_ma    = 183.5
volume_ok  = True

enter_long = (fast_ma > slow_ma) and (rsi < 70) and volume_ok
print(f"是否進場做多:{enter_long}")   # True
邏輯運算子速查:
and:全部為 True 才是 True;or:至少一個 True 就是 True;not:反轉布林值。在量化策略中,常用 and 串聯多個進場條件,確保所有篩選條件都成立才下單。

規則與注意事項

規則 正確範例 錯誤範例
首字母必須大寫 TrueFalse truefalse(NameError)
比較相等用 == if x == 1: if x = 1:(SyntaxError)
bool 可直接做算術 True + True2 邏輯上正確,但注意不要把 bool 當 int 誤用
非零數值、非空容器皆為 Truthy if [1, 2]:(成立) if []:(空串列為 Falsy,不成立)
None 是 Falsy if result is not None: if result != None:(功能正確但不符 PEP 8)
字串比較區分大小寫 "True" == "True" → True "True" == "true" → False

常見錯誤與防呆

錯誤一:布林值小寫,引發 NameError

# ❌ 錯誤寫法:true / false 是未定義的變數名稱
# NameError: name 'true' is not defined
is_ready = true
is_done  = false

# ✅ 正確寫法:True / False 首字母大寫
is_ready = True
is_done  = False

錯誤二:用 = 取代 == 做條件比較

# ❌ 錯誤寫法:= 是賦值,不能用在 if 條件
# SyntaxError: invalid syntax
signal = "BUY"
if signal = "BUY":
    print("執行買入")

# ✅ 正確寫法:if 條件用 == 比較
if signal == "BUY":
    print("執行買入")

錯誤三:對 None 結果直接做布林比較,行為非預期

# ❌ 容易誤解:直接用 == True 比較,遇到 Truthy 值可能不如預期
def get_signal():
    return None   # 尚未有訊號,回傳 None

result = get_signal()
if result == True:           # None == True 是 False,看似正確
    print("有訊號")
# 但當 result 是 1(整數)時,1 == True 也是 True,容易混淆!

# ✅ 正確防呆:明確判斷是否為 None
if result is not None:
    print(f"訊號:{result}")
else:
    print("目前沒有訊號")

進階用法

Truthy 與 Falsy:所有值都有布林意義

Python 中不只 TrueFalse 才能用在條件判斷。任何物件在 if 中都會被隱式轉換為布林值:空的容器([]{}"")、0None 都是 Falsy(等同 False);非空容器、非零數值都是 Truthy(等同 True)。用 bool() 函數可以明確查看任何值的布林結果。

# bool() 函數:查看任何值的布林轉換結果
print(bool(0))        # False(零值)
print(bool(0.0))      # False(零浮點數)
print(bool(""))       # False(空字串)
print(bool([]))       # False(空串列)
print(bool({}))       # False(空字典)
print(bool(None))     # False(空值)

print(bool(1))        # True
print(bool(-99))      # True(非零即為 Truthy)
print(bool("False"))  # True(非空字串!注意這個陷阱)
print(bool([0]))      # True(串列不空,即使內容是 0)

# 在策略中:利用 Truthy 判斷串列是否有訊號
pending_orders = []
if pending_orders:
    print("有待執行訂單")
else:
    print("目前沒有待執行訂單")   # 空串列 → Falsy,執行這行

signals = ["BUY", "HOLD"]
if signals:
    print(f"最新訊號:{signals[-1]}")   # 非空串列 → Truthy

布林值計數技巧:用加法統計條件成立次數

由於 True == 1False == 0,可以利用 sum() 搭配生成式,快速統計一組條件中有幾個成立,這在量化策略的多條件篩選與回測統計中非常實用。

# 統計一批收盤價中,有幾根 K 線收盤高於 185
closes  = [183.5, 186.2, 184.8, 187.5, 182.3, 188.1, 185.0]
count   = sum(c > 185 for c in closes)   # 每次比較回傳 True(1) 或 False(0)
print(f"高於 185 的 K 線數量:{count}")   # 3

# 統計多個策略條件成立數量(用於「評分式」入場邏輯)
rsi      = 28
macd_pos = True
vol_spike= True
above_ma = False

conditions = [
    rsi < 30,          # True  → 1
    macd_pos,          # True  → 1
    vol_spike,         # True  → 1
    above_ma,          # False → 0
]
score = sum(conditions)   # 3(4個條件中有3個成立)
print(f"條件評分:{score}/4")

if score >= 3:
    print("條件充分,考慮進場")

回傳布林值的函數設計

函數可以直接 return 一個比較運算式,結果自動就是 TrueFalse,不需要額外寫 if-else。這種簡潔寫法在設計策略條件判斷函數時非常常見。

# 策略輔助函數:直接回傳比較結果(即布林值)
def is_oversold(rsi, threshold=30):
    """RSI 是否低於超賣門檻。"""
    return rsi < threshold   # 直接回傳 True 或 False

def is_golden_cross(fast_ma, slow_ma):
    """快線是否上穿慢線(黃金交叉)。"""
    return fast_ma > slow_ma

def is_valid_signal(price, rsi, volume):
    """綜合條件:價格、RSI、成交量是否同時達標。"""
    return (price > 180) and (rsi < 35) and (volume > 1000)

# 使用函數結果直接做條件判斷
current_rsi = 27
fast        = 186.5
slow        = 184.0
vol         = 1200

if is_oversold(current_rsi) and is_golden_cross(fast, slow):
    print("RSI 超賣 + 均線黃金交叉:強力買入訊號")

# 也可以儲存布林結果再判斷
valid = is_valid_signal(185.5, 27, 1200)
print(f"訊號有效:{valid}")   # True

# 搭配 not 反轉
if not is_golden_cross(fast, slow):
    print("均線死亡交叉或尚未交叉,不進場")

煉金坊小叮嚀

布林值雖然只有兩個值,但它是整個程式邏輯的命脈。在量化策略開發中,我最常犯的問題是把 None(尚無訊號)誤當 False(明確否定)處理,結果策略在初始化時就觸發錯誤邏輯。建議養成習慣:用 is Noneis not None 判斷空值,用 ==!= 判斷數值相等,兩者語意不同,不要混用。另外,Truthy / Falsy 是 Python 非常優雅的設計,熟悉之後可以讓程式碼非常簡潔——例如 if signals:if len(signals) > 0: 更 Pythonic。最後提醒:"False"(字串)的布林值是 True,因為它是非空字串!這個陷阱在處理使用者輸入或 API 回傳字串時特別容易踩到,務必留意。

張貼留言

較新的 較舊