Python编程基础:逻辑操作与条件控制流详解
1. Python中的逻辑运算符
在Python中,逻辑运算符用于组合或修改布尔表达式的结果。主要有三种逻辑运算符:and、or 和 not。
1.1. and 逻辑与
当且仅当所有参与运算的条件都为 True 时,and 表达式的结果才为 True。只要有一个条件为 False,整个表达式的结果即为 False。
1.2. or 逻辑或
只要参与运算的条件中至少有一个为 True,or 表达式的结果就为 True。只有当所有条件都为 False 时,表达式结果才为 False。
1.3. not 逻辑非
not 运算符用于反转单个布尔表达式的值。如果表达式为 True,not 会使其变为 False;如果表达式为 False,not 会使其变为 True。
2. 逻辑运算符示例
2.1. and 运算符
user_age = 25
account_balance = 1200
# 检查用户是否符合特定条件:年龄大于18且账户余额超过1000
can_access = (user_age > 18 and account_balance > 1000)
print(f"年龄大于18且余额超过1000: {can_access}") # True
# 另一个场景:年龄大于30但余额不足500
can_afford = (user_age > 30 and account_balance > 500)
print(f"年龄大于30且余额超过500: {can_afford}") # False (因为user_age不大于30)
2.2. or 运算符
current_day = "Saturday"
is_holiday = False
# 判断今天是否休息日(周末或法定假日)
is_day_off = (current_day == "Saturday" or current_day == "Sunday" or is_holiday)
print(f"今天是休息日吗? {is_day_off}") # True
# 检查用户是否可以享受折扣(学生或VIP客户)
is_student = False
is_vip_member = True
has_discount = (is_student or is_vip_member)
print(f"用户是否可以享受折扣? {has_discount}") # True
2.3. not 运算符
is_active = False
is_empty = True
# 反转活跃状态
print(f"非活跃状态: {not is_active}") # True
# 反转空状态
print(f"非空状态: {not is_empty}") # False
3. 逻辑运算符的优先级
在复杂的布尔表达式中,运算符的执行顺序遵循特定的优先级规则:
() (括号) > 算术运算符 (如 +, -, *, /) > 比较运算符 (如 ==, >, <) > not > and > or。
为了确保运算顺序符合预期,建议在不确定时使用括号明确指定。
# 假设有三个布尔变量
condition_a = True
condition_b = False
condition_c = False
# 示例1:使用括号改变优先级
# (condition_a or condition_b) 先计算,结果为 True
# True and condition_c (False) 最终结果为 False
result_with_parentheses = (condition_a or condition_b) and condition_c
print(f"使用括号的结果: {result_with_parentheses}") # False
# 示例2:不使用括号,遵循默认优先级
# condition_b and condition_c 先计算,结果为 False
# condition_a (True) or False 最终结果为 True
result_without_parentheses = condition_a or condition_b and condition_c
print(f"不使用括号的结果: {result_without_parentheses}") # True
4. 链式比较
Python 允许使用链式比较,这使得判断一个值是否在某个区间内变得非常简洁和直观。它比使用 and 连接两个比较表达式更具可读性。
4.1. 传统比较方式
temperature = 22
# 检查温度是否在18到25摄氏度之间
is_comfortable_traditional = temperature >= 18 and temperature <= 25
print(f"传统方式:温度舒适吗? {is_comfortable_traditional}") # True
4.2. 链式比较方式
temperature = 22
# 更简洁、更符合数学习惯的写法
is_comfortable_chained = 18 <= temperature <= 25
print(f"链式方式:温度舒适吗? {is_comfortable_chained}") # True
5. 条件语句:if, elif, else
条件语句是程序根据不同条件执行不同代码块的关键,实现了程序的决策能力。
5.1. if 语句
if 语句用于在满足特定条件时执行一段代码。如果条件为 True,则执行其下的代码块;否则,跳过该代码块。
# 语法结构
# if 条件表达式:
# # 当条件为True时执行的代码(注意缩进)
current_stock = 150
if current_stock > 100:
print("库存充足,可以接受大订单。")
重要提示: Python使用缩进来定义代码块。通常推荐使用4个空格作为一个缩进级别。
5.2. if-else 语句
if-else 语句提供了两种选择路径:如果条件为 True,执行 if 块;否则(条件为 False),执行 else 块。
# 语法结构
# if 条件表达式:
# # 当条件为True时执行的代码
# else:
# # 当条件为False时执行的代码
user_input = 7
if user_input % 2 == 0:
print(f"{user_input} 是偶数。")
else:
print(f"{user_input} 是奇数。")
5.3. if-elif-else 语句
当需要处理多个互斥条件时,可以使用 if-elif-else 结构。程序会从上到下依次检查条件,一旦某个 if 或 elif 条件满足,其对应的代码块将被执行,并跳过其余的 elif 和 else 块。如果所有 if 和 elif 条件都不满足,则执行 else 块(如果存在)。
# 语法结构
# if 条件1:
# # 条件1满足时执行
# elif 条件2:
# # 条件1不满足但条件2满足时执行
# elif 条件3:
# # ...
# else:
# # 所有条件都不满足时执行
exam_score = 88
if exam_score >= 90:
print("成绩评级:A (优秀)")
elif exam_score >= 80:
print("成绩评级:B (良好)")
elif exam_score >= 70:
print("成绩评级:C (中等)")
elif exam_score >= 60:
print("成绩评级:D (及格)")
else:
print("成绩评级:F (不及格)")
# 输出:成绩评级:B (良好)
6. 嵌套的 if 语句
当一个条件满足后,需要进行更细致的二次或多次判断时,可以使用嵌套的 if 语句。这意味着一个 if 语句的代码块内部包含了另一个 if 语句。
# 示例:检查用户权限和年龄
has_login = True
access_level = "admin"
current_year = 2023
birth_year = 2000
if has_login:
print("用户已登录。")
if access_level == "admin":
print("管理员权限,可以访问所有功能。")
# 进一步检查年龄是否符合特定操作要求
if (current_year - birth_year) >= 21:
print("管理员年龄符合,允许执行敏感操作。")
else:
print("管理员年龄不足21岁,限制部分操作。")
else:
print("普通用户权限,访问受限。")
else:
print("用户未登录,请先登录。")