邏輯運算子
- 邏輯運算又稱布爾運算,常用0、1或者False、True來表示兩者的關系,
- 在理解邏輯運算之前,首先要明確邏輯常量與邏輯變數,
邏輯常量只有兩個,即0和1,用來表示兩個對立的邏輯狀態;
邏輯變數與普通代數一樣,也可以用字母、符號、數字及其組合來表示,
- 但他們之間有著本質的區別,因為邏輯常量的取值只有兩個,即0和1,沒有中間值,
Python語言支持邏輯運算子,以下假設變數:
a = 10
b = 20
| 運算子 | 邏輯運算式 | 描述 | 例子 |
|---|---|---|---|
| and | x and y | if x is False, then x【else y】 | (a and b) 回傳 20 |
| or | x or y | if x is False, then y【else x】 | (a or b) 回傳 10 |
| not | not x | if x is False, then True【else False】 | not(a and b) 回傳 False |
很多人都困惑,10 或 20 到底哪里來的,實在難以理解!
回到開頭,其實這里的 10 或 20,就是【邏輯變數】,如下圖:

驗證 10 或 20 到底是什么 bool 型別!
# 只有 0 == False,其他整數都是 True,下圖為驗證
for i in range(-12, 12):
print(i, end=",")
print("\n") # 換行
for i in range(-12, 12):
print(bool(i), end=",")
print("\n") # 換行
print(bool(1.5)) # 浮點數 float 的布爾型別
結算結果:
-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,
True,True,True,True,True,True,True,True,True,True,True,True,False,True,True,True,True,True,True,True,True,True,True,True,
True
結果顯示:
按照以上的方法進行測驗,發現只有 0 為 False,其他都是 True
顯示為True的型別:字串str、串列list、集合set、字典dict
公式套路回去:
a = 10【bool值為True】
b = 20【bool值為True】
print(a and b) 結果回傳 b,也就是20
print(a or b) 結果回傳a,也就是10
套路總結
- 邏輯運算的 本質 是 布爾運算,
- 別管出現的a、b還是 (c %= a)= 亂七八糟的,記住 0 == False,其他全部為True,再套公式,就這樣,
本文結束,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/26545.html
標籤:其他
上一篇:目標檢測自動標注生成xml檔案
