Python 中的 or:逻辑 OR 运算符详解

学习如何在 Python 中使用 OR 运算符进行逻辑运算、条件语句和短路评估,包含实用示例和最佳实践。

Python 中的 or 运算符是一个逻辑运算符,如果至少有一个操作数评估为 True,则返回 True。它是一个二元运算符,使用英文单词 "or",用于在条件语句、循环和函数逻辑中创建复合布尔表达式。

基本 or 运算符语法

or 运算符接受两个操作数,并评估至少一个是否为真。

condition1 or condition2

or 运算符当至少一个操作数为 True 时返回 True。只有当两个操作数都为 False 时才返回 False

示例 1:基本布尔表达式

bool1 = 2 > 3  # False
bool2 = 2 < 3  # True

result = bool1 or bool2
print(result)
输出:
True

示例 2:两者都为 False

bool1 = 2 > 3  # False
bool2 = 5 > 10  # False

result = bool1 or bool2
print(result)
输出:
False

当两个条件都为 False 时,or 运算符返回 False

or 运算符的真值表

理解 or 运算符如何与不同的布尔组合一起工作是至关重要的。

条件 1 条件 2 结果
True True True
True False False
False True False
False False False

or 运算符当至少一个操作数为 True 时返回 True

示例:所有真值表情况

# Case 1: True or True = True
if True or True:
    print("Case 1: True")  # This executes

# Case 2: True or False = True
if True or False:
    print("Case 2: True")  # This executes

# Case 3: False or True = True
if False or True:
    print("Case 3: True")  # This executes

# Case 4: False or False = False
if False or False:
    print("Case 4: True")
else:
    print("Case 4: False")  # This executes
输出:
Case 1: True
Case 2: True
Case 3: True
Case 4: False

Combining Multiple Conditions

The and operator is commonly used to combine multiple comparison operations in conditional statements.

Example 1: Age and License Check

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive")
else:
    print("You cannot drive")
Output:
You can drive

Example 2: Number Range Check

number = 15

if number > 10 and number < 20:
    print(f"{number} is between 10 and 20")
Output:
15 is between 10 and 20

Example 3: Multiple Conditions

a = 10
b = 10
c = -10

if a > 0 and b > 0:
    print("The numbers are greater than 0")

if a > 0 and b > 0 and c > 0:
    print("All numbers are greater than 0")
else:
    print("At least one number is not greater than 0")
Output:
The numbers are greater than 0
At least one number is not greater than 0

This example shows how and can chain multiple conditions together.

短路评估

or 运算符使用短路评估,一旦找到真值就停止,不评估剩余的操作数。

示例:演示短路

def check_first():
    print("First condition evaluated")
    return False

def check_second():
    print("Second condition evaluated")
    return True

# Short-circuit in action
if check_first() and check_second():
    print("Both are True")
else:
    print("At least one is False")
输出:
First function called
True

注意 "Second function called" 永远不会打印,因为 true_func() 返回了 True,所以 Python 跳过了对 false_func() 的评估。这种优化提高了性能并防止了不必要的计算。

Example 2: Avoiding Division by Zero

x = 0
y = 10

# Safe division check
if x != 0 and y / x > 2:
    print("y/x is greater than 2")
else:
    print("Cannot divide or condition not met")
Output:
Cannot divide or condition not met

The short-circuit evaluation prevents the division by zero error because x != 0 is False, so y / x is never evaluated.

Using and with Boolean Variables

Boolean variables can be combined directly with the and operator without comparison operators.

Example 1: Direct Boolean Check

is_logged_in = True
has_permission = True

if is_logged_in and has_permission:
    print("Access granted")
else:
    print("Access denied")
Output:
Access granted

Example 2: Multiple Boolean Flags

a = 10
b = 12
c = 0

if a and b and c:
    print("All numbers have boolean value as True")
else:
    print("At least one number has boolean value as False")
Output:
At least one number has boolean value as False

In Python, 0 evaluates to False in boolean context, while non-zero numbers evaluate to True.

链接多个 OR 操作

您可以将多个 or 运算符链接在一起,以检查变量是否匹配任何值。

示例 1:链接 OR 运算符

attendance = 85
homework_score = 90
exam_score = 88

if attendance >= 80 and homework_score >= 85 and exam_score >= 85:
    print("You passed the course with good grades")
else:
    print("Requirements not met")
输出:
Access granted

示例 2:使用 'in' 的更好替代方案

password = "SecurePass123"

has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
min_length = len(password) >= 8

if has_upper and has_lower and has_digit and min_length:
    print("Password is strong")
else:
    print("Password does not meet requirements")
输出:
Access granted

Example 3: Date Range Validation

year = 2024
month = 6
day = 15

if year > 2000 and month >= 1 and month <= 12 and day >= 1 and day <= 31:
    print("Valid date")
else:
    print("Invalid date")
Output:
Valid date

Python 'and' vs Other Languages '&&'

Unlike languages like C, C++, Java, or JavaScript that use && for logical AND, Python uses the keyword and.

Python Syntax:

x = 5
y = 10

if x < y and y < 15:
    print("Both conditions are True")

Other Languages (JavaScript/Java/C++):

// This does NOT work in Python
if (x < y && y < 15) {
    console.log("Both conditions are True");
}

Important: Attempting to use && in Python will result in a SyntaxError. Always use the keyword and in Python.

# This will cause an error
# if x > 0 && y > 0:  # SyntaxError
#     print("Error!")

# Correct Python syntax
if x > 0 and y > 0:
    print("Correct!")

Combining and with or Operator

You can mix and and or operators in the same expression, but remember that and has higher precedence than or. Use parentheses to control evaluation order.

Example 1: Without Parentheses

age = 25
has_ticket = True
is_vip = False

# and has higher precedence than or
if age >= 18 and has_ticket or is_vip:
    print("You can enter")
Output:
You can enter

This evaluates as: (age >= 18 and has_ticket) or is_vip

Example 2: With Parentheses for Clarity

score = 75
extra_credit = 10

# Explicit grouping
if (score >= 70 and score < 80) or extra_credit >= 20:
    print("Grade: B")
Output:
Grade: B

Example 3: Complex Condition

temperature = 25
is_sunny = True
is_weekend = True

if (temperature > 20 and is_sunny) or is_weekend:
    print("Good day for outdoor activities")
Output:
Good day for outdoor activities

常见用例

用例 1:输入验证

username = "alice"
password = "password123"
email = "alice@example.com"

if len(username) > 0 and len(password) >= 8 and "@" in email:
    print("Registration successful")
else:
    print("Please check your input")
输出:
Valid age

用例 2:默认值

age = 22
citizen = True
registered = True

if age >= 18 and citizen and registered:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote")
输出:
Hello, Alice!
Hello, Guest!
Hello, Guest!

用例 3:权限检查

purchase_amount = 150
is_member = True
has_coupon = True

if purchase_amount > 100 and (is_member or has_coupon):
    discount = 0.15
    final_price = purchase_amount * (1 - discount)
    print(f"You qualify for 15% discount. Final price: ${final_price}")
输出:
Access granted
Access granted
Access denied

Use Case 4: Access Control

user_role = "admin"
is_authenticated = True
session_valid = True

if is_authenticated and session_valid and user_role == "admin":
    print("Access granted to admin panel")
else:
    print("Access denied")
Output:
Access granted to admin panel

Use Case 5: Data Validation

data = [1, 2, 3, 4, 5]

if len(data) > 0 and all(isinstance(x, int) for x in data) and min(data) >= 0:
    print("Data is valid")
else:
    print("Invalid data")
Output:
Data is valid

Nested Conditions vs and Operator

Using the and operator is often cleaner than nesting multiple if statements.

Nested Approach (Less Readable):

age = 25
income = 50000

if age >= 21:
    if income >= 30000:
        print("Loan approved")
    else:
        print("Insufficient income")
else:
    print("Age requirement not met")

Using and Operator (More Readable):

age = 25
income = 50000

if age >= 21 and income >= 30000:
    print("Loan approved")
else:
    print("Requirements not met")
Output:
Loan approved

The second approach using and is more concise and easier to understand.

要避免的常见错误

错误 1:混淆 OR 与 AND

# Wrong - SyntaxError
# if x > 0 && y > 0:
#     print("Both positive")

# Correct
if x > 0 and y > 0:
    print("Both positive")

错误 2:期望布尔返回值

# Ambiguous - may not work as intended
if x > 5 and y > 3 or z < 10:
    print("Condition met")

# Better - use parentheses
if (x > 5 and y > 3) or z < 10:
    print("Condition met")

Mistake 3: Checking Multiple Values Incorrectly

x = 5

# Wrong - doesn't work as expected
# if x == 3 or 5 or 7:  # Always True!

# Correct
if x == 3 or x == 5 or x == 7:
    print("x is 3, 5, or 7")

# Even better - use 'in'
if x in [3, 5, 7]:
    print("x is 3, 5, or 7")

Mistake 4: Not Considering Short-Circuit

# Potentially unsafe
# if len(my_list) > 0 and my_list[0] > 10:  # Error if my_list doesn't exist

# Safe approach
my_list = []
if my_list and len(my_list) > 0 and my_list[0] > 10:
    print("First element is greater than 10")

最佳实践

实践 1:检查成员资格时使用 'in' 运算符

# Clearer with parentheses
if (age >= 18 and age <= 65) and (has_license or has_permit):
    print("Can drive")

实践 2:利用短路评估

# Instead of this:
# if user.age >= 18 and user.has_account and user.verified and not user.banned:
#     grant_access()

# Do this:
is_adult = user.age >= 18
has_valid_account = user.has_account and user.verified
not_banned = not user.banned

if is_adult and has_valid_account and not_banned:
    print("Access granted")

实践 3:对复杂条件使用括号

# Put the most likely to fail condition first
def cheap_check():
    return True

def expensive_operation():
    return True

if cheap_check() and expensive_operation():
    print("Both passed")

实践 4:避免混合逻辑和按位运算符

# Poor
# if a and b and c:
#     do_something()

# Better
is_authenticated = True
has_permission = True
is_active = True

if is_authenticated and has_permission and is_active:
    print("Action allowed")

亲自尝试

通过修改下面的代码来练习您学到的知识。尝试更改值和条件以查看不同的输出!

就绪
main.py
输出控制台 0 ms
// 点击"运行代码"查看结果

相关主题

常见问题

Python 中 'or' 和 '||' 有什么区别?

Python 使用关键字 or 进行逻辑 OR 运算。符号 || 用于其他语言(如 C、Java 和 JavaScript),但在 Python 中会导致 SyntaxError

or 运算符是否评估两个条件?

不总是。Python 使用短路评估——如果第一个条件是 True,则不会评估第二个条件,因为结果已经已知为 True

我可以将 or 与两个以上的条件一起使用吗?

可以,您可以链接多个条件:if a or b or c or d:。至少一个条件必须为 True,表达式才会评估为 True

or 与 and 相比的优先级是什么?

and 运算符的优先级高于 or。这意味着 a or b and c 被评估为 a or (b and c)。使用括号以提高清晰度。

如何使用 or 提供默认值?

您可以使用 or 提供默认值:name = user_input or "Guest"。如果 user_input 为假值(空、None 等),它将使用 "Guest"。

我可以将 or 与非布尔值一起使用吗?

可以。Python 在布尔上下文中评估值。or 返回第一个真值,如果所有都为假值,则返回最后一个值。如果需要显式布尔值,请使用 bool()