Python编程:从入门到实践(第3版)

> 📖 **一起读书吧!** 加入《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
# 简单的if
age = 19
if age >= 18:
print("你已经成年了")

# if-else 二选一
age = 16
if age >= 18:
print("成年人")
else:
print("未成年人")

# if-elif-else 多选一
age = 12
if age < 4:
print("免费入场")
elif age < 18:
print("门票10元")
elif age < 65:
print("门票20元")
else:
print("门票15元(老人优惠)")

官方文档:4.1. if Statementselifelse 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" # True
"cat" == "Cat" # False

# 不相等
"cat" != "dog" # True

# 数字比较
age = 18
age == 18 # True

# 多条件比较
1 < age < 100 # True(Python特色!)

# is 和 == 的区别
a = [1, 2, 3]
b = [1, 2, 3]
a == b # True(值相等)
a is b # False(不是同一个对象)

# None 判断
x = None
x is None # True(推荐用is)

3. 布尔运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
age = 25
has_ticket = True

# and — 两个都True才通过
if age >= 18 and has_ticket:
print("可以入场")

# or — 任一True就通过
if age < 5 or age > 65:
print("半价票")

# not — 取反
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: # 非空列表为True
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做出实际项目。