Python 邏輯運算子: and(&) or(|) xor(^) not

加入好友
加入社群
Python 邏輯運算子: and(&) or(|) xor(^) not - 儲蓄保險王

and運算符: A and B

必須同時為True

才會return True

Python 邏輯運算子: and(&) or(|) xor(^) not - 儲蓄保險王

1. 使用 AND 運算符

檢查一個人是否年滿18歲且持有票券。如果兩個條件都符合,則進行某些操作。

age = 20
has_ticket = True

if age > 18 and has_ticket:
    print("Allowed to enter.")
else:
    print("Not allowed to enter.")

or運算符:A or B 只要其中一個為True

return True

兩者同時為False

才會return False

Python 邏輯運算子: and(&) or(|) xor(^) not - 儲蓄保險王

2. 使用 OR 運算符

檢查是否是 VIP 或者是否有優惠券。如果滿足其中一個條件,則允許進行某些特定活動。

VIP = False
coupon = True

if VIP or coupon:
    print("Access granted to special offers.")
else:
    print("No special offers available.")

xor: A ^ B

一真一假才會return True

Python 邏輯運算子: and(&) or(|) xor(^) not - 儲蓄保險王

2. 使用 XOR 運算符: ^

檢查dict的兩個key,是否一真一假。

# 創建一個字典來表示數據特性
data_properties = {'amplitude': True, 'phase': False}

# 斷言檢查確保'amplitude''phase'正好只有一個為真
assert data_properties['amplitude'] ^ data_properties['phase'], "你給的資料不是相位就是振幅,不然就是你設定錯誤了"

print("數據檢查通過,可以進行下一步處理。")

解釋

在這段代碼中,我們使用 XOR 運算子 ^ 來確保字典 data_properties 中的 amplitude 和 phase 恰好只有一個為真。XOR 運算的特性是,當兩個操作數中只有一個為真時,結果才為真。因此,這條 assert 語句檢查的是:

  • 如果 amplitude 為 True 而 phase 為 False,或者 amplitude 為 False 而 phase 為 True,那麼條件為真,程序將繼續執行。
  • 如果 amplitude 和 phase 要麼都是 True,要麼都是 False,則條件為假,將拋出 AssertionError,並顯示設置的錯誤信息。

這種方法很適合用在需要根據特定規則進行數據驗證的場景中,確保數據的一致性和正確性。

Python 邏輯運算子: and(&) or(|) xor(^) not - 儲蓄保險王

4. 檢查資料夾是否存在並建立

這個例子使用 os 模塊來檢查一個資料夾是否存在,如果不存在則創建它。

import os

folder_path = "example_folder"

if not os.path.exists(folder_path):
    os.makedirs(folder_path)
    print(f"Folder created at: {folder_path}")
else:
    print(f"Folder already exists at: {folder_path}")

推薦hahow線上學習python: https://igrape.net/30afN

加入好友
加入社群
Python 邏輯運算子: and(&) or(|) xor(^) not - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *