本文目录导读:

我来为你介绍几个Python条件判断的实用案例,从基础到进阶:
基础条件判断案例
案例1:判断成绩等级
# 根据分数判断等级
score = int(input("请输入成绩(0-100):"))
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 70:
print("中等")
elif score >= 60:
print("及格")
else:
print("不及格")
# 更严谨的写法,包含输入验证
if 0 <= score <= 100:
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 70:
print("中等")
elif score >= 60:
print("及格")
else:
print("不及格")
else:
print("请输入0-100之间的分数")
案例2:判断闰年
year = int(input("请输入年份:"))
# 判断闰年条件:能被4整除但不能被100整除,或者能被400整除
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year}年是闰年")
else:
print(f"{year}年是平年")
实用案例
案例3:登录验证系统
# 模拟登录验证
username = input("请输入用户名:")
password = input("请输入密码:")
# 预设的用户名和密码
correct_username = "admin"
correct_password = "123456"
# 条件判断
if username == correct_username and password == correct_password:
print("登录成功!欢迎回来")
elif username != correct_username:
print("用户名错误")
elif password != correct_password:
print("密码错误")
else:
print("登录失败")
案例4:温度转换与提示
temperature = float(input("请输入温度:"))
unit = input("请输入温度单位 (C/F):").upper()
if unit == "C":
# 摄氏度转华氏度
fahrenheit = (temperature * 9/5) + 32
print(f"{temperature}°C = {fahrenheit:.1f}°F")
# 温度提示
if temperature >= 35:
print("⚠️ 高温预警!注意防暑")
elif temperature >= 25:
print("☀️ 天气炎热,适合游泳")
elif temperature >= 15:
print("🌤️ 天气舒适,适合户外活动")
elif temperature >= 5:
print("🌥️ 天气凉爽,注意添衣")
else:
print("❄️ 天气寒冷,注意保暖")
elif unit == "F":
# 华氏度转摄氏度
celsius = (temperature - 32) * 5/9
print(f"{temperature}°F = {celsius:.1f}°C")
else:
print("请输入正确的温度单位 (C 或 F)")
复杂业务逻辑案例
案例5:购物折扣计算器
# 根据购买金额和会员等级计算折扣
total_amount = float(input("请输入购物总金额:"))
membership = input("请输入会员等级 (普通/银卡/金卡/钻石):")
# 判断折扣
if total_amount >= 1000:
if membership == "钻石":
discount = 0.7 # 7折
points = total_amount * 2 # 双倍积分
elif membership == "金卡":
discount = 0.8 # 8折
points = total_amount * 1.5
elif membership == "银卡":
discount = 0.85 # 85折
points = total_amount * 1.2
else:
discount = 0.9 # 9折
points = total_amount
elif total_amount >= 500:
if membership == "钻石":
discount = 0.75
points = total_amount * 1.8
elif membership == "金卡":
discount = 0.85
points = total_amount * 1.3
elif membership == "银卡":
discount = 0.9
points = total_amount * 1.1
else:
discount = 0.95
points = total_amount
else:
if membership == "钻石":
discount = 0.8
points = total_amount * 1.5
elif membership == "金卡":
discount = 0.88
points = total_amount * 1.2
else:
discount = 1.0 # 不打折
points = total_amount
final_amount = total_amount * discount
print(f"原价:¥{total_amount:.2f}")
print(f"折扣:{int((1-discount)*100)}%")
print(f"实付:¥{final_amount:.2f}")
print(f"获得积分:{int(points)}")
案例6:BMI健康评估系统
# 计算BMI指数并给出健康建议
height = float(input("请输入身高(米):"))
weight = float(input("请输入体重(公斤):"))
# 计算BMI
bmi = weight / (height ** 2)
print(f"您的BMI指数为:{bmi:.1f}")
# 判断健康状况
if bmi < 18.5:
print("⚠️ 体重过轻")
advice = "建议增加营养摄入,适当锻炼增肌"
elif bmi < 24:
print("✅ 体重正常")
advice = "请保持健康的饮食习惯和运动"
elif bmi < 28:
print("⚠️ 超重")
advice = "建议控制饮食,增加运动量"
elif bmi < 32:
print("❌ 肥胖(一级)")
advice = "建议专业健康指导,合理饮食配合运动"
elif bmi < 37:
print("❌ 肥胖(二级)")
advice = "建议咨询医生,制定科学的减重计划"
else:
print("‼️ 极度肥胖(三级)")
advice = "强烈建议寻求医疗帮助,进行专业干预"
print(f"健康建议:{advice}")
简化代码技巧
使用三元运算符
# 传统写法
age = 20
if age >= 18:
status = "成年"
else:
status = "未成年"
# 三元运算符写法
status = "成年" if age >= 18 else "未成年"
使用字典优化条件判断
# 代替多个if-elif
def get_day_name(day_number):
days = {
1: "星期一",
2: "星期二",
3: "星期三",
4: "星期四",
5: "星期五",
6: "星期六",
7: "星期日"
}
return days.get(day_number, "无效的输入")
print(get_day_name(3)) # 输出:星期三
编写建议
- 按照优先级排序:把最可能满足的条件放在前面,提高效率
- 使用括号明确优先级:复杂条件用括号分组,提高可读性
- 避免过深的嵌套:嵌套超过3层时,考虑重构
- 保持条件互斥:确保else分支能覆盖所有未处理的情况
- 输入验证:对用户输入进行合法性检查
这些案例覆盖了从基础到实用的Python条件判断场景,你可以根据实际需求进行调整和组合使用。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播