Python基础指南之if条件判断语句的三种基本结构详解
一、开篇:程序为什么"聪明"
程序之所以能做出不同的反应,核心就在于条件判断。用户登录了吗?余额够吗?数据合法吗?——每一个"如果…就…"的背后,都是if语句在工作。
条件判断是编程中最基本也是最强大的控制结构。无论你的程序多么复杂,它本质上都是在做一系列的判断和分支决策。今天这篇文章,我们就来学习Python中if条件判断语句的三种基本结构,从语法基础到最佳实践,为后续的流程控制打下坚实的基础。
# 程序就是无数个"如果...就..."
# 如果用户已登录 → 显示主页
# 如果余额足够 → 完成支付
# 如果数据非法 → 返回错误提示
# Python中这一切都用 if 语句实现
if condition:
do_something()
学习if语句,本质上是在学习如何让程序"思考"和"决策"。
二、if语句的第一种结构:单分支
2.1 基本语法
单分支if是最简单的条件判断结构——条件满足就执行,不满足就跳过。
# 单分支 if 的基本语法
# if 条件:
# 代码块
age = 20
if age >= 18:
print("你已经成年了!") # 这行只在age>=18时执行
print("可以独立注册账号") # 这行同上
print("程序继续执行...") # 这行总是执行
# 注意缩进!Python靠缩进来确定哪些代码属于if块
# 上面两个print缩进了,属于if块
# 最后一个print没缩进,不属于if块
2.2 缩进规则详解
Python使用缩进来定义代码块,这是Python最独特的语法特征之一:
# 缩进规则
# 1. 用4个空格(或1个Tab,但推荐空格)
# 2. 同一代码块的所有语句缩进必须一致
# 3. if后面的冒号 : 不能省略
# ✅ 正确:统一用4个空格缩进
if True:
print("第一行")
print("第二行")
print("第三行")
# ✅ 也正确:冒号后面可以直接写语句(不推荐)
if True: print("一行搞定")
# ❌ 错误:不一致的缩进
# if True:
# print("4个空格")
# print("6个空格") # IndentationError!
# ❌ 错误:忘记冒号
# if True # SyntaxError!
# print("xxx")
# ❌ 错误:需要缩进但没缩进
# if True:
# print("xxx") # IndentationError!
2.3 if的"条件":真值测试
if后面的条件表达式会被隐式转换为bool值:
# if后面的条件不需要显式地写 == True
# Python会自动对它做真值测试
# 下面两种写法等价:
if is_valid == True: # 不推荐的写法
pass
if is_valid: # 推荐的写法(简洁)
pass
# 各种"真值"和"假值"在if中的表现
# 假值:False, None, 0, 0.0, "", [], (), {}, set()
# 真值:除假值外的所有对象
test_values = [
True, False, # 布尔值
None, # None
1, 0, -1, 0.0, 3.14, # 数字
"hello", "", " ", # 字符串
[1, 2], [], # 列表
(1,), (), # 元组
{"a": 1}, {}, # 字典
]
for v in test_values:
if v:
print(f"{v!r:15} → 真值 ✅")
else:
print(f"{v!r:15} → 假值 ❌")
2.4 if条件中的常见表达式
# 1. 比较表达式
score = 85
if score >= 60:
print("及格了")
# 2. 成员检查
name = "张三"
if name in ["张三", "李四", "王五"]:
print("在名单中")
# 3. 身份检查
result = None
if result is None:
print("没有返回值")
# 4. 逻辑组合
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("允许入场")
# 5. 函数调用
def is_admin(user):
return user.get("role") == "admin"
user = {"name": "张三", "role": "admin"}
if is_admin(user):
print("欢迎,管理员!")
# 6. 字符串方法
email = "test@example.com"
if email.endswith(".com"):
print("商业邮箱")
# 7. 链式比较
x = 50
if 0 <= x <= 100:
print("x在合法范围内")
# 8. 取反
is_banned = False
if not is_banned:
print("账户正常")
2.5 单分支的典型应用场景
# 场景1:输入验证
def process_age(age):
if age < 0 or age > 150:
print(f"⚠️ 警告:年龄 {age} 无效,已调整为默认值")
age = 18
print(f"处理年龄: {age}")
return age
process_age(25) # 正常
process_age(-5) # 触发警告
process_age(200) # 触发警告
# 场景2:异常数据跳过
def clean_data(data):
"""清洗数据:跳过无效记录"""
cleaned = []
for item in data:
if item is None or item == "":
continue # 跳过无效数据
cleaned.append(item)
return cleaned
# 场景3:日志记录
def transfer_money(from_account, to_account, amount):
if amount > 10000:
print(f"🔔 大额转账提醒: {amount}元") # 额外监控
# 执行转账...
print(f"转账 {amount} 元:{from_account} → {to_account}")
三、if语句的第二种结构:双分支 if-else
3.1 基本语法
当条件满足时做一件事,不满足时做另一件事,用if-else:
# if-else 的基本语法
# if 条件:
# 条件为真时执行的代码块
# else:
# 条件为假时执行的代码块
age = 16
if age >= 18:
print("您可以进入网吧")
else:
print("未成年人不允许进入网吧")
# if 和 else 的缩进级别必须相同!
3.2 if-else 的经典应用
# 场景1:登录验证
def login(username, password):
correct_username = "admin"
correct_password = "123456"
if username == correct_username and password == correct_password:
print("✅ 登录成功!欢迎回来")
return True
else:
print("❌ 用户名或密码错误")
return False
login("admin", "123456") # 成功
login("admin", "wrong") # 失败
# 场景2:数据校验
def validate_email(email):
if "@" in email and "." in email.split("@")[-1]:
print(f"✅ {email} 是有效的邮箱格式")
return True
else:
print(f"❌ {email} 格式不正确")
return False
validate_email("test@example.com") # ✅
validate_email("invalid-email") # ❌
# 场景3:奇偶判断
def check_even_odd(n):
if n % 2 == 0:
print(f"{n} 是偶数")
return "even"
else:
print(f"{n} 是奇数")
return "odd"
# 场景4:文件存在性检查
import os
def read_file_safe(filename):
if os.path.exists(filename):
with open(filename, 'r', encoding='utf-8') as f:
return f.read()
else:
print(f"⚠️ 文件 {filename} 不存在")
return None
3.3 if-else 的嵌套
在if或else的代码块中,可以再包含if语句:
# if-else 嵌套结构
def check_number(n):
if n >= 0:
if n == 0:
print(f"{n} 是零")
else:
print(f"{n} 是正数")
else:
print(f"{n} 是负数")
check_number(10) # 正数
check_number(0) # 零
check_number(-5) # 负数
# 更复杂的嵌套
def classify_triangle(a, b, c):
"""三角形分类"""
# 先检查是否为三角形
if a + b > c and a + c > b and b + c > a:
if a == b == c:
return "等边三角形"
else:
if a == b or b == c or a == c:
return "等腰三角形"
else:
return "普通三角形"
else:
return "不是三角形"
print(classify_triangle(3, 3, 3)) # 等边三角形
print(classify_triangle(3, 3, 4)) # 等腰三角形
print(classify_triangle(3, 4, 5)) # 普通三角形
print(classify_triangle(1, 2, 5)) # 不是三角形
注意:嵌套层级不宜过深。一般超过3层就应该考虑重构。
四、if语句的第三种结构:多分支 if-elif-else
4.1 基本语法
当有多个互斥的条件需要判断时,使用if-elif-else:
# if-elif-else 的基本语法
# if 条件1:
# 条件1为真时执行
# elif 条件2:
# 条件1为假且条件2为真时执行
# elif 条件3:
# 条件1、2都为假且条件3为真时执行
# ...
# else:
# 以上条件都为假时执行
#
# elif 可以有任意多个
# else 是可选的
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"分数 {score} → 等级 {grade}")
4.2 执行逻辑:从上到下,匹配即停
# if-elif-else 的核心执行逻辑:
# 1. 从上到下逐个检查条件
# 2. 第一个为True的条件对应的代码块被执行
# 3. 后面的条件不会再检查
# 用代码证明
def demonstrate_elif_order(score):
"""演示elif的执行顺序"""
if score >= 90:
print(f"score={score} → 匹配了 >= 90")
elif score >= 80:
print(f"score={score} → 匹配了 >= 80")
elif score >= 60:
print(f"score={score} → 匹配了 >= 60")
else:
print(f"score={score} → 匹配了 else")
demonstrate_elif_order(95) # 只匹配第一个(>=90),不会输出>=80
demonstrate_elif_order(85) # 只匹配>=80
demonstrate_elif_order(65) # 只匹配>=60
demonstrate_elif_order(55) # 匹配else
# ⚠️ 条件顺序非常重要!
# 如果把范围最宽的条件放前面,后面的条件永远不会被执行
def bad_order(score):
"""错误的条件顺序"""
if score >= 60: # 这个条件太宽!
print("及格")
elif score >= 90: # 永远不会被执行!因为>=90已经包含在>=60中
print("优秀")
# ...
bad_order(95) # 输出"及格"——预期应该是"优秀"!
4.3 elif是else if的缩写
# Python的 elif 等价于其他语言的 else if
# 但它更简洁
# Python写法
if a > 0:
sign = "正"
elif a < 0:
sign = "负"
else:
sign = "零"
# 等价于嵌套的 if-else(只是更冗长)
if a > 0:
sign = "正"
else:
if a < 0:
sign = "负"
else:
sign = "零"
# 显然 elif 更清晰!
4.4 无需else的elif
有时你不需要兜底的else:
# 没有else的if-elif
def get_discount(level):
"""根据会员等级返回折扣(非会员无折扣)"""
if level == "gold":
return 0.8 # 金卡8折
elif level == "silver":
return 0.9 # 银卡9折
elif level == "bronze":
return 0.95 # 铜卡95折
# 没有else——非会员返回None表示无折扣
return None
print(get_discount("gold")) # 0.8
print(get_discount("silver")) # 0.9
print(get_discount("normal")) # None
五、三种结构的选型指南
选型决策树
问题:需要做条件判断吗?
├── 不需要 → 不用if
└── 需要
└── 有几个分支?
├── 1个(条件满足做,不满足跳过)
│ → 用单分支 if
│ → 例:if error: log(error)
│
├── 2个(二选一)
│ → 用双分支 if-else
│ → 例:if valid: process() else: reject()
│
└── 3个及以上(多选一)
→ 用多分支 if-elif-else
→ 例:评分等级、菜单选择、权限级别
六、if语句的性能考量
6.1 条件的排列顺序影响效率
# 把最可能命中的条件放前面
# 把计算量小的条件放前面
def classify_user_fast(user):
"""高效的条件排列"""
# 大多数用户是普通用户
if user.role == "normal": # 90%的用户,放在第一
return "普通用户"
elif user.role == "vip": # 8%的用户
return "VIP用户"
elif user.role == "admin": # 2%的用户
return "管理员"
else:
return "未知"
# 利用短路求值优化
def is_valid_user(user):
"""先检查快的条件"""
# user存在是最快的检查,放前面
if user is None or not user.get("active") or user.get("banned"):
return False
return True
6.2 字典映射替代长if-elif
当elif分支非常多且都是简单的值映射时,考虑用字典:
# ❌ 长if-elif链
def get_status_text(code):
if code == 200:
return "成功"
elif code == 301:
return "永久重定向"
elif code == 302:
return "临时重定向"
elif code == 400:
return "请求错误"
elif code == 401:
return "未授权"
elif code == 403:
return "禁止访问"
elif code == 404:
return "未找到"
elif code == 500:
return "服务器内部错误"
else:
return "未知状态码"
# ✅ 字典映射(更简洁、更快)
HTTP_STATUS = {
200: "成功",
301: "永久重定向",
302: "临时重定向",
400: "请求错误",
401: "未授权",
403: "禁止访问",
404: "未找到",
500: "服务器内部错误",
}
def get_status_text_v2(code):
return HTTP_STATUS.get(code, "未知状态码")
# 字典映射也支持函数
def handle_create():
return "创建操作"
def handle_delete():
return "删除操作"
def handle_update():
return "更新操作"
OPERATIONS = {
"create": handle_create,
"delete": handle_delete,
"update": handle_update,
}
def execute(operation):
handler = OPERATIONS.get(operation)
if handler:
return handler()
else:
return "未知操作"
七、实战案例
7.1 BMI计算器
def calculate_bmi(weight, height):
"""
计算BMI并给出健康建议
weight: 体重(公斤)
height: 身高(米)
"""
if height <= 0 or weight <= 0:
return "输入数据无效"
bmi = weight / (height ** 2)
# 使用多分支if-elif-else评定等级
if bmi < 18.5:
category = "偏瘦"
advice = "建议增加营养摄入,适当增重"
elif bmi < 24:
category = "正常"
advice = "恭喜!您的体重在健康范围内,请继续保持"
elif bmi < 28:
category = "偏胖"
advice = "建议控制饮食,增加运动量"
elif bmi < 32:
category = "肥胖"
advice = "建议制定减重计划,咨询专业医生"
else:
category = "重度肥胖"
advice = "⚠️ 建议尽快就医,制定专业减重方案"
return {
"bmi": round(bmi, 1),
"category": category,
"advice": advice
}
# 测试
test_data = [
(45, 1.70), # 偏瘦
(65, 1.70), # 正常
(78, 1.70), # 偏胖
(90, 1.70), # 肥胖
(120, 1.70), # 重度肥胖
]
for weight, height in test_data:
result = calculate_bmi(weight, height)
print(f"体重={weight}kg 身高={height}m → "
f"BMI={result['bmi']}, {result['category']}")
print(f" 建议: {result['advice']}")
print()
7.2 简易ATM取款机
class SimpleATM:
"""简易ATM,演示if语句的三种结构"""
def __init__(self, balance=1000):
self.balance = balance
def withdraw(self, amount):
"""取款操作 —— 展示条件判断的完整流程"""
# 单分支:检查输入有效性
if amount <= 0:
print("❌ 取款金额必须大于0")
return False
# 双分支:检查余额
if amount > self.balance:
print(f"❌ 余额不足!当前余额: {self.balance}元")
return False
else:
self.balance -= amount
print(f"✅ 取款成功!")
print(f" 取款: {amount}元")
print(f" 余额: {self.balance}元")
# 多分支:给额外的建议
if self.balance == 0:
print("⚠️ 余额已为零,请及时充值")
elif self.balance < 100:
print("💡 余额不足100元,建议尽快充值")
elif self.balance > 5000:
print("💡 余额较多,注意资金安全")
return True
def deposit(self, amount):
"""存款操作"""
if amount <= 0:
print("❌ 存款金额必须大于0")
return False
else:
self.balance += amount
print(f"✅ 存款成功!存款: {amount}元, 余额: {self.balance}元")
return True
# 使用
atm = SimpleATM(1000)
atm.withdraw(300) # 正常取款
atm.withdraw(800) # 余额不足
atm.deposit(5000) # 存款
atm.withdraw(5800) # 大额取款
7.3 表单验证器
class FormValidator:
"""表单验证器 —— 多个if条件组合判断"""
def __init__(self, data):
self.data = data
self.errors = []
def validate(self):
"""执行验证,收集所有错误"""
# 多个单分支if:不是互斥的,每个条件都检查
if not self.data.get("username"):
self.errors.append("用户名不能为空")
elif len(self.data.get("username", "")) < 3:
self.errors.append("用户名至少3个字符")
if not self.data.get("password"):
self.errors.append("密码不能为空")
elif len(self.data.get("password", "")) < 6:
self.errors.append("密码至少6个字符")
if self.data.get("password") != self.data.get("confirm_password"):
self.errors.append("两次输入的密码不一致")
email = self.data.get("email", "")
if email:
if "@" not in email:
self.errors.append("邮箱格式不正确")
elif "." not in email.split("@")[-1]:
self.errors.append("邮箱域名不完整")
else:
self.errors.append("邮箱不能为空")
# 返回验证结果
if self.errors:
return False, self.errors
else:
return True, ["表单验证通过"]
def is_valid(self):
"""快捷方法:是否验证通过"""
# 单分支:利用 validate 的返回值
valid, _ = self.validate()
return valid
# 使用
form = FormValidator({
"username": "ab", # 太短
"password": "123", # 太短
"confirm_password": "1234", # 不一致
"email": "invalid", # 格式错误
})
valid, messages = form.validate()
if not valid:
print("❌ 表单验证失败:")
for msg in messages:
print(f" - {msg}")
else:
print("✅ 验证通过")
八、常见错误与最佳实践
8.1 常见错误
# 错误1:用 = 代替 ==
# if x = 10: # SyntaxError!
# print(x)
x = 10
if x == 10: # ✅ 正确
print(x)
# 错误2:忘记冒号
# if x > 0 # SyntaxError!
# print(x)
if x > 0: # ✅ 正确
print(x)
# 错误3:缩进不一致
# if x > 0:
# print("a")
# print("b") # IndentationError!
# 错误4:不必要的 == True/False
# ❌
if is_valid == True:
pass
# ✅
if is_valid:
pass
# ❌
if is_valid == False:
pass
# ✅
if not is_valid:
pass
# 错误5:条件顺序不当
score = 95
# ❌ 永远不会输出"优秀"
if score >= 60:
grade = "及格"
elif score >= 90:
grade = "优秀"
# ...
# ✅ 从严格到宽松排列
if score >= 90:
grade = "优秀"
elif score >= 60:
grade = "及格"
# ...
# 错误6:把字符串当作布尔
# ❌ if "active" or "pending": 总是True!
# 等价于 if "active":
status = "active"
if status == "active" or status == "pending": # ✅
pass
# 或者
if status in ("active", "pending"): # ✅ 更好
pass
8.2 最佳实践
# 实践1:提前返回,减少嵌套
# ❌ 深层嵌套
def process_order_bad(order):
if order is not None:
if order.get("items"):
if order.get("user"):
if order["user"].get("verified"):
# 实际逻辑...
return "处理成功"
return "处理失败"
# ✅ 提前返回(Guard Clauses)
def process_order_good(order):
if order is None:
return "订单不存在"
if not order.get("items"):
return "订单为空"
if not order.get("user"):
return "订单无用户信息"
if not order["user"].get("verified"):
return "用户未验证"
# 所有异常情况已处理,现在处理正常逻辑
return "处理成功"
# 实践2:条件表达式扁平化
# ❌ 多重否定
if not (not is_banned):
pass
# ✅ 直接表达
if is_banned:
pass
# 实践3:利用Python真值规则
# ❌ 显式检查长度
if len(items) > 0:
process(items)
# ✅ 直接利用真值测试
if items:
process(items)
# 实践4:条件复杂时提取为函数
# ❌ 条件太长
if user.age >= 18 and user.is_verified and not user.is_banned and \
user.subscription_status == "active" and user.balance >= 100:
allow_access()
# ✅ 提取为函数
def can_access(user):
return (
user.age >= 18
and user.is_verified
and not user.is_banned
and user.subscription_status == "active"
and user.balance >= 100
)
if can_access(user):
allow_access()
九、本章小结
本文我们系统学习了Python if条件判断语句的三种基本结构:
- 单分支 if:条件满足时执行,不满足时跳过。适用于"需要时做额外处理"的场景,如日志记录、异常数据过滤。
- 双分支 if-else:二选一的分支结构。适用于"是A还是B"的二元决策,如验证通过/失败、登录成功/失败。
- 多分支 if-elif-else:多选一的分支结构。从上到下依次检查条件,命中即停止。适用于等级评定、菜单选择等多条件场景。
我们还学习了:
- Python的缩进规则及其重要性
- 真值测试的原理
- elif条件顺序的影响
- 字典映射替代长if-elif链的优化技巧
- 提前返回(Guard Clauses)减少嵌套的最佳实践
if语句是编程中最基础也最重要的控制结构。掌握好它,你就掌握了让程序"思考"的能力。⌨️ 下一篇文章,我们将深入学习if-elif-else多条件分支的高级用法和技巧!
到此这篇关于Python基础指南之if条件判断语句的三种基本结构详解的文章就介绍到这了,更多相关Python if条件判断语句内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
aws 通过boto3 python脚本打pach的实现方法
这篇文章主要介绍了aws 通过boto3 python脚本打pach的实现方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-05-05
使用Python开发你的第一个AI工具服务MCP Server
MCP(Model Context Protocol)是 Anthropic 推出的开放协议,让 AI 模型能够安全地连接外部数据源和工具,本文将带你从零理解 MCP 协议,并用 Python 开发一个完整的 MCP Server,让 Claude 等 AI 助手直接调用你编写的工具,需要的朋友可以参考下2026-04-04
Flask使用Pyecharts在单个页面展示多个图表的方法
这篇文章主要介绍了Flask使用Pyecharts在单个页面展示多个图表的方法,在Flask页面展示echarts,主要有两种方法,文中给大家介绍的非常详细,需要的朋友可以参考下2019-08-08
Django-simple-captcha验证码包使用方法详解
这篇文章主要介绍了Django-simple-captcha验证码包使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-11-11


最新评论