使用逻辑运算符创建复杂条件(或者不是)
Tip
有关更多详细信息,请参阅 “文本和图像 ”选项卡!
有时,单个条件不足以做出决定。 你可能想要检查两件事是否都是真的,还是至少一个是真的。 例如,可能需要验证帐户是活动 帐户和 资金帐户,或者用户是管理员 还是 审查者。
Python的逻辑运算符允许将多个条件合并为一个表达式。
三个逻辑运算符
| Operator | 它的作用是什么 | Example | Result |
|---|---|---|---|
and |
True
仅 当 双方 均为 True |
True and False |
False |
or |
True 如果 至少一 侧为 True |
True or False |
True |
not |
翻转布尔值 | not True |
False |
使用和(必须满足所有条件)
当必须满足所有条件才能运行代码块时使用 and :
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Entry granted.")
else:
print("Entry denied.")
Output:
Entry granted.
使用或(必须满足至少一个条件)
当任一条件足以运行代码块时使用 or 。 在日常语言中,“或”通常表示“一个或另一个,但不是两者”。但是,在Python,“或”表示“一个或另一个或两者”。
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("The office is closed.")
Output:
The office is closed.
不使用(反转条件)
运算符 not 反转布尔值。 如果条件为 True,则变为 False,反之亦然。 如果要检查是否存在条件,则此运算符非常有用。
is_logged_in = False
if not is_logged_in:
print("Please log in to continue.")
Output:
Please log in to continue.
结合使用运算符
可以在单个表达式中合并not和or合并and。 始终使用括号对条件进行分组,并使代码更易于阅读:
score = 85
has_extra_credit = True
is_past_due = False
# Example: Pass if (Score is high OR extra credit is earned) AND the work isn't late
if (score >= 90 or has_extra_credit) and not is_past_due:
print("Requirement met.")
避免快捷方式错误
将单个变量与多个值进行比较时,可能会想编写如下所示的内容:
# Incorrect: This code will not work as intended
if score == 90 or 100:
print("You got an A!")
在本例中,Python首先评估score == 90,即TrueFalse或 。 然后,计算 100结果始终 True如此。 非零数和无空字符串始终按TruePython计算。 因此,无论其值如何score,条件始终True是。 始终显式比较每个值:
# Correct: Each value is compared explicitly
if score == 90 or score == 100:
print("You got an A!")