第5章 if 语句
本章目标:学习条件测试、if 语句的各种结构(if / if-else / if-elif-else),以及如何结合列表使用 if 语句。
5.1 一个简单示例
python
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
输出:
Audi
BMW
Subaru
Toyota
5.2 条件测试
条件测试 :值为 True 或 False 的表达式,是 if 语句的核心。
5.2.1 检查是否相等
python
>>> car = 'bmw'
>>> car == 'bmw'
True
>>> car = 'audi'
>>> car == 'bmw'
False
一个等号
=是赋值 ,两个等号==是问询(值相等吗?)。
5.2.2 检查是否相等时不考虑大小写
Python 检查是否相等时区分大小写:
python
>>> car = 'Audi'
>>> car == 'audi'
False
使用 lower() 忽略大小写比较(不会修改原变量):
python
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
>>> car
'Audi'
网站常用此法:用户输入的用户名先转为小写,再与既有用户名的小写版本比较,确保唯一性。
5.2.3 检查是否不相等
python
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
!=表示"不等于"。
5.2.4 比较数字
python
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
5.2.5 检查多个条件
and --- 两个条件都为 True 时整个表达式为 True:
python
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 22
>>> age_0 >= 21 and age_1 >= 21
True
or --- 至少一个条件为 True 时整个表达式为 True:
python
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False
5.2.6 检查特定值是否包含在列表中 --- in
python
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False
5.2.7 检查特定值是否不包含在列表中 --- not in
python
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
5.2.8 布尔表达式
布尔表达式就是条件测试的别名,值为 True 或 False:
python
game_active = True
can_edit = False
常用于跟踪程序状态。
5.3 if 语句
5.3.1 简单的 if 语句
python
if conditional_test:
do something
示例:
python
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
如果条件为 True,执行所有缩进的代码行。
5.3.2 if-else 语句
python
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
if-else 结构总是会执行两个操作中的一个。
5.3.3 if-elif-else 结构
依次检查每个条件,遇到第一个通过的条件就执行对应的代码块,并跳过余下测试:
python
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
推荐在 if-elif-else 中只设置值,后面统一用 print 输出,更易维护。
5.3.4 使用多个 elif 代码块
python
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
5.3.5 省略 else 代码块
python
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
用
elif代替else更清晰,避免意外捕获无效数据。
5.3.6 测试多个条件
关键区别:
if-elif-else:只执行一个代码块(遇到通过的测试就跳过后续)- 多个独立
if:执行所有为 True 的条件对应代码
python
# 多个独立 if --- 检查所有条件
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
# Adding mushrooms.
# Adding extra cheese.
python
# if-elif-else --- 只执行第一个通过的
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
# 只有 Adding mushrooms.(extra cheese 被跳过了)
5.4 使用 if 语句处理列表
5.4.1 检查特殊元素
python
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
5.4.2 确定列表不是空的
python
requested_toppings = []
if requested_toppings: # 非空列表 → True
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else: # 空列表 → False
print("Are you sure you want a plain pizza?")
在 if 语句中:列表名直接作为条件,非空为 True,空为 False。
5.4.3 使用多个列表
python
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
# Adding mushrooms.
# Sorry, we don't have french fries.
# Adding extra cheese.
5.5 设置 if 语句的格式
PEP 8 建议:在比较运算符两边各加一个空格。
python
# ✅ 推荐
if age < 4:
# ❌ 不推荐
if age<4:
动手试一试
5-1 ~ 5-2 条件测试
python
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
# 更多测试
print("\n--- String tests ---")
print('hello' == 'hello') # True
print('hello' == 'Hello') # False
print('hello'.lower() == 'hello') # True
print("\n--- Number tests ---")
print(10 > 5) # True
print(10 < 5) # False
print(10 >= 10) # True
print(10 <= 9) # False
print("\n--- and/or tests ---")
print((10 > 5) and (5 > 3)) # True
print((10 > 5) and (5 < 3)) # False
print((10 > 5) or (5 < 3)) # True
print("\n--- in/not in tests ---")
names = ['alice', 'bob']
print('alice' in names) # True
print('dave' not in names) # True
5-3 ~ 5-5 外星人颜色
python
# 5-3
alien_color = 'green'
if alien_color == 'green':
print("You earned 5 points!")
# 5-4
if alien_color == 'green':
print("You earned 5 points!")
else:
print("You earned 10 points!")
# 5-5
if alien_color == 'green':
print("You earned 5 points!")
elif alien_color == 'yellow':
print("You earned 10 points!")
else:
print("You earned 15 points!")
5-6 人生的不同阶段
python
age = 25
if age < 2:
print("婴儿")
elif age < 4:
print("蹒跚学步")
elif age < 13:
print("儿童")
elif age < 20:
print("青少年")
elif age < 65:
print("成年人")
else:
print("老年人")
5-7 喜欢的水果
python
favorite_fruits = ['banana', 'apple', 'strawberry']
if 'banana' in favorite_fruits:
print("You really like bananas!")
if 'apple' in favorite_fruits:
print("You really like apples!")
if 'orange' in favorite_fruits:
print("You really like oranges!")
if 'strawberry' in favorite_fruits:
print("You really like strawberries!")
if 'grape' in favorite_fruits:
print("You really like grapes!")
5-8 ~ 5-9 以特殊方式跟管理员打招呼
python
usernames = ['admin', 'eric', 'alice', 'bob', 'carol']
if usernames:
for username in usernames:
if username == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + username.title() + ", thank you for logging in again.")
else:
print("We need to find some users!")
5-10 检查用户名
python
current_users = ['admin', 'eric', 'Alice', 'Bob', 'Carol']
new_users = ['Alice', 'David', 'Eve', 'BOB', 'Frank']
current_users_lower = [user.lower() for user in current_users]
for new_user in new_users:
if new_user.lower() in current_users_lower:
print("Username '" + new_user + "' is taken. Please choose another.")
else:
print("Username '" + new_user + "' is available.")
5-11 序数
python
numbers = list(range(1, 10))
for number in numbers:
if number == 1:
print("1st")
elif number == 2:
print("2nd")
elif number == 3:
print("3rd")
else:
print(str(number) + "th")
代码块汇总
python
# 条件测试
== # 相等
!= # 不相等
> # 大于
< # 小于
>= # 大于等于
<= # 小于等于
and # 与(两个条件都成立)
or # 或(至少一个成立)
in # 值在列表中
not in # 值不在列表中
# if 语句结构
if condition: # 简单 if
...
if condition: # if-else
...
else:
...
if condition: # if-elif-else
...
elif condition:
...
else:
...
# 在条件中使用列表
if list_name: # 列表非空为 True
if value in list_name: # 值在列表中
if value not in list_name: # 值不在列表中
常见错误 / 陷阱
| 错误 | 说明 | 解决 |
|---|---|---|
误用 = 代替 == |
赋值 vs 相等判断 | 判断用 == |
| 忘记冒号 | if condition: 缺冒号 |
加冒号 |
| 逻辑错误:只执行了一个 if | 该用多个独立 if 却用了 elif | 需要多项操作时用多个 if |
| 空列表未检查 | 直接 for 循环空列表不报错,但无输出 | 用 if list: 先检查 |
| 大小写不匹配 | 'Audi' == 'audi' 为 False |
用 lower() 统一比较 |
复习要点
- 条件测试是值为
True/False的表达式 -
==检查相等,!=检查不相等 - 字符串比较区分大小写,用
lower()忽略大小写 - 数字比较:
>,<,>=,<=,==,!= -
and/or组合多个条件 -
in/not in检查列表中是否存在值 -
if-elif-else只执行一个代码块;多个独立if可执行多个 - 列表名在 if 语句中:非空 → True,空 → False
- 用
elif代替else更清晰安全 - 比较运算符两边各加一个空格(PEP 8)
学习时的困惑
🤔 = 和 == 搞混:老毛病了
写 JavaScript 和 Python 都犯过这个错------条件判断里写了一个 = 而不是 ==。Python 会直接报语法错误,不像 JavaScript 那样默默赋值,这点还算友好。
🤔 if-elif-else VS 多个 if:搞不清什么时候用哪个
书上说 if-elif-else 只执行一个分支,多个 if 执行多个。一开始觉得"那为什么不全部用多个 if?"后来想明白了------如果条件互斥就用 elif,如果条件不互斥就用多个 if。 比如判断分数段:A/B/C/D 是互斥的,用 elif;检查一个字符串里是否包含多个关键词,用多个 if。
🤔 列表名直接当条件:第一次看到有点懵
python
if requested_toppings:
当时心想"这不是列表吗,怎么当布尔值用了?"后来才知道 Python 里空列表是 False,非空是 True。这个技巧写自动化脚本时经常用------检查任务队列是否为空。
💡 lower() 处理输入:工作中非常实用
用户输入"Python"和"python"都能匹配上,后面处理工单关键词搜索时肯定会用到。
跟我工作的关系
| 知识点 | 能用在哪 |
|---|---|
if / elif / else |
自动化脚本中的条件分支:根据任务状态执行不同操作 |
in / not in |
检查配置项是否在白名单里,过滤非法输入 |
列表名当条件 if list: |
检查待处理工单队列是否为空,有任务才执行 |
and / or |
组合多个条件,比如"时间到了且任务未执行"才触发 |
lower() 统一比较 |
用户输入的关键词匹配,不区分大小写 |
实战小项目(TODO)
写一个简易的任务状态判断脚本:定义几个任务状态值,用 if-elif 判断当前状态并输出对应的操作建议。