邏輯運算子

邏輯運算子用於組合多個條件。

and 運算

# 兩個條件都要為 True
age = 25
has_id = True

can_enter = age >= 18 and has_id
print(can_enter)  # True

or 運算

# 其中一個條件為 True 即可
is_vip = False
has_ticket = True

can_enter = is_vip or has_ticket
print(can_enter)  # True

not 運算

# 取反
is_raining = False
go_outside = not is_raining
print(go_outside)  # True

組合使用

age = 20
is_student = True
is_senior = False

# 學生或長者可享優惠
discount = is_student or is_senior  # True

# 成年且為學生
adult_student = age >= 18 and is_student  # True

短路求值

# and: 第一個為 False 就不會檢查第二個
# or: 第一個為 True 就不會檢查第二個

result = False and expensive_function()  # 不會執行 expensive_function
result = True or expensive_function()    # 不會執行 expensive_function

練習

判斷一個人是否可以投票(年滿 18 且為公民)

💻 程式碼編輯器
📤 執行結果
等待執行...
← 上一課 下一課 →