Python 条件判断:让程序学会"做选择"
引言:从"自动门"到"智能决策"
想象你走进一家商场,自动门感应到你的存在,自动打开。这背后就是一个简单的条件判断:如果检测到有人,就开门;否则保持关闭。
计算机之所以"智能",不是因为它们真的会思考,而是因为它们能根据预设条件自动执行不同的操作。Python 的 if 语句就是让程序学会"做选择"的核心工具。
今天,我们将彻底掌握条件判断的精髓,让你的程序能够像经验丰富的决策者一样,根据不同情况做出最合适的响应。
一、if 语句:程序的"十字路口"
1.1 最简单的 if
age = 20
if age >= 18:
print('your age is', age)
print('adult')生活化理解:这就像你对朋友说"如果明天下雨,我们就改天再去野餐"。条件满足(下雨)→ 执行行动(改天)。
执行逻辑:
- 判断
age >= 18是否为真 - 如果为真,执行缩进的代码块
- 如果为假,跳过缩进的代码块
1.2 冒号和缩进:Python 的"语法规则"
if age >= 18: # ← 注意冒号!
print('adult') # ← 4个空格缩进(或1个Tab)常见错误:
# ❌ 缺少冒号
if age >= 18
print('adult')
# ❌ 没有缩进
if age >= 18:
print('adult')
# ❌ 缩进不一致
if age >= 18:
print('adult') # 2个空格
print('age') # 4个空格(混乱)生活化理解:冒号像"那么"的意思——"如果...那么..."。缩进像"分组"——属于同一组的代码用相同缩进。
1.3 if-else:非此即彼
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')生活化理解:就像考试结果——"如果及格了,就庆祝;否则,就继续努力"。
执行流程:
条件为真 → 执行 if 块 → 跳过 else 块
条件为假 → 跳过 if 块 → 执行 else 块1.4 if-elif-else:多路选择
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')elif 是 "else if" 的缩写,可以有多个:
score = 85
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 60:
print('及格')
else:
print('不及格')生活化理解:就像餐厅点餐——"如果有牛排,要牛排;否则如果有鸡排,要鸡排;否则如果有鱼排,要鱼排;否则吃素食"。
1.5 从上往下匹配:重要的执行特点
age = 20
if age >= 6:
print('teenager') # ← 会执行这里!
elif age >= 18:
print('adult') # ← 永远不会执行
else:
print('kid')输出:teenager
为什么? 因为 age >= 6 为真,执行后就跳出了整个 if 结构,后面的 elif 和 else 都被忽略了。
生活化理解:就像查字典——找到第一个匹配的解释就停止,不会继续看后面的解释。
正确的写法(范围从小到大):
age = 20
if age >= 18: # 先判断最严格的条件
print('adult')
elif age >= 6: # 再判断次严格的
print('teenager')
else:
print('kid')二、条件的"真"与"假"
2.1 比较运算符
| 运算符 | 含义 | 示例 | 结果 |
|---|---|---|---|
== | 等于 | 5 == 5 | True |
!= | 不等于 | 5 != 3 | True |
> | 大于 | 5 > 3 | True |
< | 小于 | 5 < 3 | False |
>= | 大于等于 | 5 >= 5 | True |
<= | 小于等于 | 5 <= 3 | False |
特别注意:= 是赋值,== 才是比较!
# ❌ 错误:把比较写成赋值
if x = 5: # SyntaxError
# ✅ 正确
if x == 5:
print('x is 5')2.2 逻辑运算符
| 运算符 | 含义 | 示例 | 结果 |
|---|---|---|---|
and | 两者都为真 | True and False | False |
or | 至少一个为真 | True or False | True |
not | 取反 | not True | False |
# 复合条件
age = 25
income = 5000
if age >= 18 and income >= 3000:
print('可以申请信用卡')
if age < 18 or income < 3000:
print('暂不符合条件')
if not (age < 18):
print('已成年')2.3 简写形式:Python 的" truthiness"
Python 中,任何值都可以判断真假:
# 非零数字为真
if 1: # True
if -1: # True
if 0: # False
# 非空字符串为真
if 'hello': # True
if '': # False
# 非空列表为真
if [1, 2]: # True
if []: # False
# None 为假
if None: # False简写示例:
x = []
# 传统写法
if len(x) > 0:
print('有元素')
# 简写
if x:
print('有元素')三、input():与用户交互
3.1 input() 的基本用法
name = input('请输入你的名字:')
print('你好,', name)注意:input() 返回的永远是字符串(str)!
3.2 常见的类型错误
# ❌ 错误:字符串和整数不能直接比较
birth = input('请输入出生年份:') # 输入 1982,得到 '1982'(字符串)
if birth < 2000: # TypeError: '<' not supported between 'str' and 'int'
print('00前')
# ✅ 正确:先转换为整数
birth = int(input('请输入出生年份:')) # int() 将字符串转为整数
if birth < 2000:
print('00前')
else:
print('00后')3.3 转换失败的处理
# 用户输入 'abc' 时
birth = int('abc') # ValueError: invalid literal for int()
# 防御性写法
s = input('请输入出生年份:')
if s.isdigit(): # 检查是否为纯数字
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
else:
print('输入无效,请输入数字')四、常见误区与陷阱
4.1 误区一:忘记冒号
# ❌ 错误
if age >= 18
print('adult')
# ✅ 正确
if age >= 18:
print('adult')4.2 误区二:缩进不一致
# ❌ 错误:混用空格和Tab,或缩进不对齐
if age >= 18:
print('adult')
print('age')
# ✅ 正确:统一用4个空格
if age >= 18:
print('adult')
print('age')4.3 误区三:条件顺序错误
# ❌ 错误:范围大的条件在前
score = 95
if score >= 60:
print('及格') # 95分输出"及格",不合理!
elif score >= 80:
print('良好')
elif score >= 90:
print('优秀')
# ✅ 正确:范围小的条件在前
score = 95
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 60:
print('及格')4.4 误区四:混淆 = 和 ==
# ❌ 错误:把赋值当比较
if x = 5: # SyntaxError
# ✅ 正确
if x == 5:
print('x is 5')4.5 误区五:链式比较的错误理解
# Python 特有的链式比较(正确且优雅)
age = 25
if 18 <= age < 60: # 等价于 age >= 18 and age < 60
print('工作年龄')
# 其他语言可能需要分开写
if age >= 18 and age < 60:
print('工作年龄')五、实战案例
案例 1:BMI 计算器
height = 1.75 # 米
weight = 80.5 # 千克
bmi = weight / (height ** 2)
print(f'你的 BMI 指数:{bmi:.1f}')
if bmi < 18.5:
print('过轻')
elif bmi < 25:
print('正常')
elif bmi < 28:
print('过重')
elif bmi < 32:
print('肥胖')
else:
print('严重肥胖')案例 2:简单登录系统
# 预设的用户名和密码
correct_username = 'admin'
correct_password = '123456'
username = input('用户名:')
password = input('密码:')
if username == correct_username and password == correct_password:
print('登录成功!')
elif username != correct_username:
print('用户名不存在')
else:
print('密码错误')案例 3:成绩等级评定
score = float(input('请输入成绩(0-100):'))
if score < 0 or score > 100:
print('输入无效,成绩应在 0-100 之间')
elif score >= 90:
grade = 'A'
comment = '优秀'
elif score >= 80:
grade = 'B'
comment = '良好'
elif score >= 70:
grade = 'C'
comment = '中等'
elif score >= 60:
grade = 'D'
comment = '及格'
else:
grade = 'F'
comment = '不及格'
if 0 <= score <= 100:
print(f'等级:{grade},评价:{comment}')案例 4:智能推荐系统
weather = input('今天天气如何?(晴/雨/雪):').strip()
temperature = int(input('今天温度多少度?'))
if weather == '晴':
if temperature > 30:
print('天气炎热,建议去游泳或待在空调房')
elif temperature > 20:
print('天气舒适,适合户外运动或野餐')
else:
print('天气较冷,建议室内活动')
elif weather == '雨':
if temperature < 10:
print('可能下雪,注意保暖')
else:
print('雨天路滑,建议在家看书或看电影')
elif weather == '雪':
print('可以堆雪人、打雪仗,注意防滑')
else:
print('未知天气,请重新输入')六、动手练习
练习 1:解释为什么下面的代码输出 teenager 而不是 adult
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')答案:因为 age >= 6 为真,执行后跳出了 if 结构,elif 和 else 不再执行。
练习 2:修正下面的代码,使其能正确判断年龄阶段
age = 20
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')总结
| 概念 | 核心要点 |
|---|---|
| if 语句 | 条件为真时执行代码块 |
| if-else | 非此即彼的二选一 |
| if-elif-else | 多路选择,从上往下匹配 |
| 冒号 | if/elif/else 后必须有冒号 |
| 缩进 | 统一用 4 个空格,表示代码块 |
| 比较运算符 | ==, !=, >, <, >=, <= |
| 逻辑运算符 | and, or, not |
| input() | 返回字符串,需要类型转换 |
| 条件顺序 | 范围小的条件放前面 |
记住:if 语句让程序学会做选择,冒号和缩进是语法的关键,条件顺序决定了执行的结果。