【蓝桥杯7天速成】第五章:Python选择结构深度解析,从逻辑运算到实战应用

Python选择结构深度解析:从逻辑运算到实战应用

1. 条件表达式与逻辑运算

1.1 关系运算符

运算符描述示例结果
>大于5 > 3True
<小于2 < 1False
==等于5 == 5True
!=不等于3 != 2True
>=大于等于4 >= 4True
<=小于等于5 <= 3False

1.2 逻辑运算符特性

# 短路运算示例
a = 10
print(a < 5 and print("不会执行"))  # 左边为False立即终止
print(a > 5 or print("不会执行"))   # 左边为True立即终止

# 运算结果类型验证
x = 5 or 0      # 5 (返回第一个真值)
y = 0 and 3      # 0 (返回第一个假值)

2. 选择结构进阶应用

2.1 嵌套条件判断

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

2.2 多条件优化方案

# 使用elif简化嵌套
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 60:
    print("C")
else:
    print("D")

3. 逻辑运算优先级

3.1 运算顺序规则

  1. 算术运算 (+, -, *, /)
  2. 关系运算 (>, <, ==, !=)
  3. 逻辑非 (not)
  4. 逻辑与 (and)
  5. 逻辑或 (or)

3.2 括号使用规范

# 易错示例
if (a > 5 and b < 3) or c == 0:  # 明确运算顺序

4. 综合实战案例

4.1 闰年判断公式

year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year}年是{'闰' if is_leap else '平'}年")

4.2 日期星期计算

# 蔡勒公式应用
y, m, d = 2023, 8, 15
if m < 3:
    m += 12
    y -= 1
h = (d + 13*(m+1)//5 + y + y//4 - y//100 + y//400) % 7
weekdays = ["六","日","一","二","三","四","五"]
print(f"该日期是星期{weekdays[h]}")

5. 编程训练题

5.1 成绩奖励系统

'''
奖励规则:
1. 任意单科满分
2. 两科90+ 
3. 三科80+
满足任一条件即可获奖
'''
chinese = 95
math = 92
english = 88

condition1 = (chinese==100) or (math==100) or (english==100)
condition2 = (chinese>90 and math>90) or (chinese>90 and english>90) or (math>90 and english>90)
condition3 = (chinese>80) and (math>80) and (english>80)

if condition1 or condition2 or condition3:
    print("获得小红花!")

5.2 购物方案优化

'''
预算X元购买6/5/4元三种商品:
- 优先购买最多数量
- 必须刚好用完预算
'''
x = 27
a = b = c = 0
mod = x % 4

if mod == 0:
    c = x//4
elif mod == 1:
    c = x//4 -1
    b = 1
elif mod == 2:
    c = x//4 -1
    a = 1
else:
    c = x//4 -2
    a, b = 1, 1

print(f"6元商品:{a}个,5元商品:{b}个,4元商品:{c}个")

6. 常见问题解答

Q:如何避免条件判断错误?

  1. 使用括号明确运算顺序
  2. 优先处理边界条件
  3. 添加调试打印语句验证中间结果

Q:多条件判断如何优化?

# 使用集合运算优化
scores = [85, 92, 78]
if sum(1 for s in scores if s == 100) >= 1:
    print("有满分科目")

if sum(1 for s in scores if s >90) >= 2:
    print("两科90+")

Q:如何处理复杂逻辑条件?

# 将复杂条件拆解为变量
is_condition1 = (a > 10) and (b < 5)
is_condition2 = (c % 2 == 0) or (d == 0)
if is_condition1 and is_condition2:
    # 执行代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

monday_CN

72小时打磨,值得1元认可

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值