一、引言
Python 提供了简洁的条件表达式写法,也就是三元运算符!让代码更简洁!
💡 值1 if 条件 else 值2 → 条件成立用值1,不成立用值2!
二、三元运算符基本用法
# 基本语法
result = value1 if condition else value2
# 例子:判断成年或未成年
age = 18
status = "成年人" if age >= 18 else "未成年人"
print(status)
等价的 if-else 写法
# 上面的三元运算符等价于:
age = 18
if age >= 18:
status = "成年人"
else:
status = "未成年人"
print(status)
三、实际例子
例子 1:判断及格或不及格
score = 75
result = "及格" if score >= 60 else "不及格"
print(result)
例子 2:求两个数的最大值
a = 10
b = 20
max_num = a if a > b else b
print(f"较大的数是:{max_num}")
例子 3:求三个数的最大值
a = 10
b = 20
c = 15
# 可以嵌套使用(但要注意可读性)
max_num = a if (a > b and a > c) else (b if b > c else c)
print(f"最大的数是:{max_num}")
# 不过更推荐用 max() 函数
max_num = max(a, b, c)
print(f"用 max() 更简单:{max_num}")
例子 4:判断是奇数还是偶数
num = int(input("请输入一个整数:"))
result = "偶数" if num % 2 == 0 else "奇数"
print(f"这是一个{result}")
例子 5:判断是否是闰年
year = int(input("请输入年份:"))
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
result = "闰年" if is_leap else "平年"
print(f"{year}年是{result}")
四、使用场景与注意事项
✅ 适合使用的场景
# 1. 简单的条件赋值
score = 75
grade = "及格" if score >= 60 else "不及格"
# 2. 简单的输出
print("及格" if score >= 60 else "不及格")
# 3. 列表推导式中
nums = [1, 2, 3, 4, 5]
result = ["偶数" if n % 2 == 0 else "奇数" for n in nums]
❌ 不适合使用的场景
# ❌ 复杂逻辑不要用(可读性差)
# 不要写成这样
x = 10
result = "A" if x > 90 else ("B" if x > 80 else ("C" if x > 60 else "D"))
# ✅ 还是用 if-elif-else 更清晰
if x > 90:
result = "A"
elif x > 80:
result = "B"
elif x > 60:
result = "C"
else:
result = "D"
五、综合实战例子
例子:简单的石头剪刀布
import random
choices = ["石头", "剪刀", "布"]
computer = random.choice(choices)
player = input("请输入(石头/剪刀/布):")
print(f"电脑出了:{computer}")
# 简单判断输赢
if player == computer:
result = "平局"
elif (player == "石头" and computer == "剪刀") or \
(player == "剪刀" and computer == "布") or \
(player == "布" and computer == "石头"):
result = "你赢了"
else:
result = "你输了"
print(result)
六、课后练习题
# 练习 1:用三元运算符判断一个数是正数还是负数
# 练习 2:用三元运算符求两个数的最小值
# 练习 3:输入一个数,用三元运算符判断是否是 3 的倍数
总结
通过本章学习,你应该已经掌握了「条件表达式与三元运算符」的相关知识。
三元运算符很简洁,但复杂逻辑还是用 if-else 更清晰!恭喜你完成模块3,开始学习循环!