【Python自學】邏輯運算子的用法and/or/not
本篇整理「邏輯運算子」的用法
什麼是邏輯運算子?
簡單而言,可以分成這三個:and、or、not
「and且,or或,not不,其實也挺直觀的,不論是從中文還是英文,直接從它們的意思去理解,就可以大概猜到它們的作用。」
常見於條件語句(if/else)當中,一樣是布林值的應用。
1、and(且)
兩個條件都要 True,結果才會是
True
簡單來說:條件A與條件B都要是true,那最後結果才會是true。但凡有一個是false,那結果就是false。
如下表
True True
→ True
True False
→ False
False True
→ False
False False
→ False
例子:
age =
20
has_ticket
= True
if
age >= 18 and has_ticket:
print("可以進場")
else:
print("不可以進場")
程式執行的結果:可以進場
只有「成年」而且「有票」才能進場。
換句或說:
你成年了但沒有票不能進場!
你沒有票但成年了不能進場!
你沒有票也未成年那當然更不能進場!
2、or(或)
只要有一個條件是 True,結果就會是
True
簡單來說:條件A與條件B只要有一個是true,那最後結果就會是true。
如下表
True True
→ True
True False
→ True
False True
→ True
False False
→ False
舉例來說:
is_member
= False
has_coupon
= True
if
is_member or has_coupon:
print("享有折扣")
else:
print("不享有折扣")
程式執行的結果:享有優惠
簡言之,就是:【只要「是會員」或「有折價券」,就可以打折。】
3、not(反向 / 取反)
not true 就是false ;not false 就是 true
True → False
False → True
例子:
is_raining
= False
if
not is_raining:
print("可以出門散步")
else:
print("帶雨傘喔")
程式執行的結果:可以出門散步
not 用來表示「相反狀態」。
4、綜合示範(搭配括號多重判斷)
age =
17
is_student
= True
has_permission
= False
if
(age < 18 and is_student) or has_permission:
print("可參加活動")
else:
print("無法參加")
程式執行的結果:可以參加
判斷邏輯說明:
(age < 18 and is_student) → True and
True → True
True or has_permission → True or False →
True
→ 可參加活動
留言
張貼留言