

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)本讲内容
- if-elif-else 条件判断
- 条件测试(比较、成员、布尔)
- 使用if语句处理列表
- 条件表达式(三元运算符)
- match语句(Python 3.10+)
学习目标
让程序学会做判断 🧠
1. if-elif-else 基础
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| age = 19 if age >= 18: print("你已经成年了")
age = 16 if age >= 18: print("成年人") else: print("未成年人")
age = 12 if age < 4: print("免费入场") elif age < 18: print("门票10元") elif age < 65: print("门票20元") else: print("门票15元(老人优惠)")
|
官方文档:4.1. if Statements — elif 是 else if 的缩写。
2. 条件测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| "cat" == "cat" "cat" == "Cat"
"cat" != "dog"
age = 18 age == 18
1 < age < 100
a = [1, 2, 3] b = [1, 2, 3] a == b a is b
x = None x is None
|
3. 布尔运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| age = 25 has_ticket = True
if age >= 18 and has_ticket: print("可以入场")
if age < 5 or age > 65: print("半价票")
if not has_ticket: print("请买票")
|
4. 使用if语句处理列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print("加蘑菇") if 'pepperoni' in requested_toppings: print("加意大利香肠")
requested_toppings = [] if requested_toppings: for topping in requested_toppings: print(f" 加 {topping}") else: print("你想要普通芝士披萨吗?")
|
5. 条件表达式(Pythonic写法)
1 2 3
| age = 20 status = "成年人" if age >= 18 else "未成年" print(status)
|
6. match语句(Python 3.10+)
1 2 3 4 5 6 7 8 9
| status = "student"
match status: case "student": print("学费半价") case "teacher": print("免费入场") case _: print("全价票")
|
官方文档:4.7. match Statements — 类似其他语言的switch-case。
📚 官方文档参考
🎓 AI 编程实战课程
程序员晚枫专注AI编程培训,通过 《50讲 · AI编程训练营》,让小白也能用AI做出实际项目。