MK
摩柯社区 - 一个极简的技术知识社区
AI 面试

Python中如何检查多个条件

2024-03-242.1k 阅读

使用逻辑运算符检查多个条件

在Python中,逻辑运算符 andornot 是检查多个条件时常用的工具。它们允许我们组合多个布尔表达式,以实现更复杂的条件判断。

and 运算符

and 运算符用于连接两个或多个条件,只有当所有条件都为 True 时,整个表达式才为 True。如果其中任何一个条件为 False,则整个表达式为 False。其语法如下:

condition1 and condition2 and... and conditionN

例如,假设我们要检查一个数是否在某个范围内,可以这样写:

num = 15
if num > 10 and num < 20:
    print("The number is in the range.")

在这个例子中,num > 10num < 20 这两个条件都必须为 Trueif 语句中的代码块才会执行。如果 num 是 5,那么 num > 10False,整个 and 表达式就为 False,代码块不会执行。

or 运算符

or 运算符同样用于连接多个条件,但只要其中有一个条件为 True,整个表达式就为 True。只有当所有条件都为 False 时,表达式才为 False。语法如下:

condition1 or condition2 or... or conditionN

比如,我们要检查一个人是否符合参与某项活动的年龄要求,只要满足其中一个年龄段即可:

age = 35
if age >= 18 or age <= 60:
    print("You are eligible to participate.")

这里,age >= 18age <= 60 只要有一个为 True,整个 or 表达式就为 Trueif 语句中的代码块就会执行。

not 运算符

not 运算符用于对一个布尔值取反。如果原条件为 True,使用 not 后变为 False;如果原条件为 False,使用 not 后变为 True。语法为:

not condition

例如,我们要检查一个数是否不在某个范围内:

num = 25
if not (num > 10 and num < 20):
    print("The number is not in the range.")

这里,先判断 num > 10 and num < 20,由于 num 为 25,此条件为 False,再使用 not 取反,变为 True,所以 if 语句中的代码块会执行。

逻辑运算符的优先级

在复杂的条件表达式中,逻辑运算符是有优先级顺序的。not 的优先级最高,其次是 and,最后是 or。例如:

a = True
b = False
c = True
result = not a and b or c

根据优先级,先计算 not a,结果为 False。然后计算 False and b,结果为 False。最后计算 False or c,结果为 True。所以 result 的值为 True

如果要改变优先级,可以使用括号。括号内的表达式会先被计算。例如:

a = True
b = False
c = True
result = not (a and b) or c

这里先计算 a and b,结果为 False,再对其取反,变为 True,最后 True or c,结果还是 True

使用 all()any() 函数检查多个条件

除了逻辑运算符,Python 还提供了 all()any() 这两个内置函数来检查多个条件。这两个函数接受一个可迭代对象(如列表、元组等)作为参数。

all() 函数

all() 函数用于检查可迭代对象中的所有元素是否都为 True。如果可迭代对象中的所有元素都为 True(或者可迭代对象为空),all() 函数返回 True;否则返回 False

conditions = [True, True, True]
if all(conditions):
    print("All conditions are True.")

在这个例子中,conditions 列表中的所有元素都是 True,所以 all(conditions) 返回 Trueif 语句中的代码块会执行。

如果列表中有一个 False 元素:

conditions = [True, False, True]
if all(conditions):
    print("All conditions are True.")
else:
    print("Not all conditions are True.")

此时,all(conditions) 返回 Falseelse 分支的代码块会执行。

any() 函数

any() 函数则与 all() 函数相反,它检查可迭代对象中是否至少有一个元素为 True。如果可迭代对象中至少有一个元素为 Trueany() 函数返回 True;如果可迭代对象为空或者所有元素都为 False,则返回 False

conditions = [False, False, True]
if any(conditions):
    print("At least one condition is True.")

这里,conditions 列表中有一个 True 元素,所以 any(conditions) 返回 Trueif 语句中的代码块会执行。

如果列表中所有元素都是 False

conditions = [False, False, False]
if any(conditions):
    print("At least one condition is True.")
else:
    print("All conditions are False.")

此时,any(conditions) 返回 Falseelse 分支的代码块会执行。

使用生成器表达式与 all()any()

all()any() 函数还可以与生成器表达式一起使用,这在处理大量数据时非常有用,因为生成器表达式不会一次性将所有数据加载到内存中。

例如,假设我们有一个很大的文件,每行表示一个数字,我们要检查所有数字是否都大于 10:

def read_numbers_from_file(file_path):
    with open(file_path, 'r') as file:
        for line in file:
            yield int(line.strip())


file_path = 'numbers.txt'
if all(num > 10 for num in read_numbers_from_file(file_path)):
    print("All numbers are greater than 10.")
else:
    print("Some numbers are not greater than 10.")

在这个例子中,num > 10 for num in read_numbers_from_file(file_path) 是一个生成器表达式,它会逐行读取文件中的数字,并对每个数字进行条件判断。all() 函数会在生成器生成的每个值上进行检查,而不会一次性将整个文件内容读入内存。

同样,使用 any() 函数检查文件中是否至少有一个数字大于 10:

if any(num > 10 for num in read_numbers_from_file(file_path)):
    print("At least one number is greater than 10.")
else:
    print("All numbers are less than or equal to 10.")

if - elif - else 结构中检查多个条件

if - elif - else 结构是Python中常用的条件判断结构,它可以用于检查多个条件,并根据不同条件执行不同的代码块。

基本 if - elif - else 结构

if - elif - else 结构的基本语法如下:

if condition1:
    # 当 condition1 为 True 时执行的代码块
    pass
elif condition2:
    # 当 condition1 为 False 且 condition2 为 True 时执行的代码块
    pass
else:
    # 当所有条件都为 False 时执行的代码块
    pass

例如,根据学生的成绩给出相应的等级评定:

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D")

在这个例子中,首先检查 score >= 90,如果为 False,再检查 score >= 80,依此类推。如果所有 ifelif 的条件都为 False,则执行 else 中的代码块。

嵌套 if - elif - else 结构

if - elif - else 结构可以嵌套使用,以处理更复杂的条件逻辑。例如,根据学生的成绩和出勤情况给出最终评定:

score = 85
attendance = 90  # 出勤率,以百分比表示
if score >= 90:
    if attendance >= 95:
        print("Excellent!")
    else:
        print("Good, but improve attendance.")
elif score >= 80:
    if attendance >= 90:
        print("Very good.")
    else:
        print("Need to improve both score and attendance.")
else:
    print("Work harder.")

在这个例子中,外层的 if - elif - else 结构根据成绩进行初步判断,内层的 if - else 结构则根据出勤率进一步细化评定。

多个条件在 if - elif - else 中的组合

我们也可以在 ifelif 条件中使用逻辑运算符组合多个条件。例如,根据商品的价格和库存情况决定是否促销:

price = 100
stock = 50
if (price > 150 and stock > 100) or (price < 80 and stock < 30):
    print("Offer a promotion.")
elif price > 120 and stock > 80:
    print("Consider a small discount.")
else:
    print("No promotion for now.")

这里,if 条件中使用了 or 运算符连接两个条件组合,分别表示价格高且库存多,或者价格低且库存少的情况。elif 条件则检查价格较高且库存较多的情况。

使用字典映射检查多个条件

在Python中,我们可以使用字典映射来根据不同的条件执行不同的操作。这种方法通过将条件值作为字典的键,将相应的操作作为字典的值来实现。

简单的字典映射示例

假设我们有一个程序,根据用户输入的数字执行不同的操作。我们可以这样实现:

def operation1():
    print("Performing operation 1.")


def operation2():
    print("Performing operation 2.")


def operation3():
    print("Performing operation 3.")


operation_map = {
    1: operation1,
    2: operation2,
    3: operation3
}

user_input = 2
if user_input in operation_map:
    operation_map[user_input]()
else:
    print("Invalid input.")

在这个例子中,operation_map 字典将数字 1、2、3 分别映射到 operation1operation2operation3 函数。当用户输入一个数字后,程序检查该数字是否在字典的键中,如果存在,则调用相应的函数。

使用字典映射处理复杂条件

我们还可以将字典映射与条件判断结合,处理更复杂的情况。例如,根据学生的成绩范围和性别给出不同的反馈:

def feedback_for_high_score_male():
    print("Great job, young man!")


def feedback_for_high_score_female():
    print("Well done, young lady!")


def feedback_for_low_score_male():
    print("Keep working hard, young man.")


def feedback_for_low_score_female():
    print("Keep working hard, young lady.")


score = 85
gender ='male'
feedback_map = {
    ('high', 'male'): feedback_for_high_score_male,
    ('high', 'female'): feedback_for_high_score_female,
    ('low','male'): feedback_for_low_score_male,
    ('low', 'female'): feedback_for_low_score_female
}

if score >= 80:
    score_category = 'high'
else:
    score_category = 'low'

if (score_category, gender) in feedback_map:
    feedback_map[(score_category, gender)]()
else:
    print("Invalid combination.")

在这个例子中,feedback_map 字典的键是成绩范围和性别的元组,值是相应的反馈函数。程序先根据成绩确定成绩范围,然后根据成绩范围和性别在字典中查找并调用相应的反馈函数。

基于类和方法的条件检查

在面向对象编程中,我们可以通过类和方法来封装条件检查逻辑,使代码更加模块化和可维护。

简单类中的条件检查

假设我们有一个表示员工的类,根据员工的工作年限和绩效评估给出不同的奖励:

class Employee:
    def __init__(self, years_of_service, performance_rating):
        self.years_of_service = years_of_service
        self.performance_rating = performance_rating

    def get_bonus(self):
        if self.years_of_service >= 5 and self.performance_rating >= 4:
            return "You get a 20% bonus!"
        elif self.years_of_service >= 3 and self.performance_rating >= 3:
            return "You get a 10% bonus!"
        else:
            return "No bonus this year."


employee1 = Employee(6, 4)
print(employee1.get_bonus())

在这个例子中,Employee 类有一个 get_bonus 方法,该方法根据员工的工作年限和绩效评估来决定是否给予奖励以及奖励的比例。

继承和多态在条件检查中的应用

通过继承和多态,我们可以进一步优化条件检查逻辑。假设我们有一个基类 Shape,以及两个子类 CircleRectangle。我们可以根据形状的类型执行不同的面积计算方法:

import math


class Shape:
    def calculate_area(self):
        pass


class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return math.pi * self.radius ** 2


class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width


shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
    if isinstance(shape, Circle):
        print(f"The circle has an area of {shape.calculate_area()}")
    elif isinstance(shape, Rectangle):
        print(f"The rectangle has an area of {shape.calculate_area()}")

在这个例子中,Shape 类是基类,CircleRectangle 类继承自 Shape 类并实现了各自的 calculate_area 方法。通过 isinstance 函数检查对象的类型,然后调用相应的 calculate_area 方法来计算面积。

总结

在Python中检查多个条件有多种方法,每种方法都有其适用场景。逻辑运算符 andornot 适用于简单的条件组合;all()any() 函数则在处理可迭代对象中的多个条件时非常方便;if - elif - else 结构是最常用的条件判断结构,可处理多种条件分支;字典映射可以通过键值对的方式简洁地实现条件与操作的映射;基于类和方法的条件检查则适用于面向对象编程,使代码更加模块化和可维护。在实际编程中,需要根据具体需求选择合适的方法来检查多个条件,以编写高效、可读的代码。