Python 逻辑运算符
Python 逻辑运算符
逻辑运算符用于组合条件语句。Python 有三个逻辑运算符:
and 与运算符
and 关键字是一个逻辑运算符,用于组合条件语句。只有当两个条件都为真时,整个表达式才为真。
实例
测试 a 是否大于 b,并且 c 是否大于 a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
亲自试一试 »
or 或运算符
or 关键字是一个逻辑运算符,用于组合条件语句。至少需要一个条件为真,整个表达式才为真。
实例
测试 a 是否大于 b,或者 a 是否大于 c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
亲自试一试 »
not 非运算符
not 关键字是一个逻辑运算符,用于反转条件语句的结果。
组合多个运算符
您可以在单个表达式中组合多个逻辑运算符。Python 会先计算 not,然后计算 and,最后计算 or。
示例
组合使用 and、or 和 not:
age = 25
is_student = False
has_discount_code = True
if (age < 18 or age > 65) and not is_student or has_discount_code:
print("Discount applies!")
亲自试一试 »
真值表
理解逻辑运算符如何与不同值一起使用:
与运算符真值表
| 条件 1 | 条件 2 | 结果 |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
或运算符真值表
| 条件 1 | 条件 2 | 结果 |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
使用括号使语句更清晰
当组合多个逻辑运算符时,请使用括号来明确您的意图并控制运算顺序。
示例
使用括号表示复杂条件:
temperature = 25
is_raining = False
is_weekend = True
if (temperature > 20 and not is_raining) or is_weekend:
print("Great day for outdoor activities!")
亲自试一试 »
更多示例
实例
用户身份验证检查:
username = "Tobias"
password = "secret123"
is_verified = True
if username and password and is_verified:
print("Login successful")
else:
print("Login failed")
亲自试一试 »
实例
使用逻辑运算符进行范围检查:
score = 85
if score >= 0 and score <= 100:
print("Valid score")
else:
print("Invalid score")
亲自试一试 »

