第12集:if-else条件语句
本集学习目标
- 掌握if-else语句的语法和用法
- 理解else语句的作用和执行时机
- 学会使用if-else处理二选一的情况
- 掌握条件表达式(三元运算符)的用法
- 通过实际练习掌握if-else语句的使用
为什么需要if-else?
在第11集中,我们学习了if语句,它只能在条件为True时执行代码。但如果条件为False时也要执行某些代码,我们该怎么办呢?
这就是if-else语句的作用!
示例对比
只用if语句:
age = 20
if age >= 18:
print("你已经成年了")
if age < 18:
print("你还是未成年")使用if-else语句:
age = 20
if age >= 18:
print("你已经成年了")
else:
print("你还是未成年")显然,if-else语句更简洁、更易读!
if-else语句的基本语法
if 条件:
# 条件为True时执行的代码块
代码块1
代码块2
else:
# 条件为False时执行的代码块
代码块3
代码块4
# 这里的代码总是会执行
后续代码语法要点:
if和else都是Python关键字,必须小写if和else后都必须有冒号:if和else下面的代码必须缩进if和else的代码块只能执行其中一个
执行流程图
开始
↓
判断条件
↓
True → 执行if代码块 ──────┐
↓ ↓
False → 执行else代码块 ────→ 继续
↓
执行后续代码
↓
结束基本示例
示例1:判断正负数
number = -5
if number > 0:
print(f"{number} 是正数")
else:
print(f"{number} 不是正数")输出:
-5 不是正数示例2:判断奇偶数
number = 7
if number % 2 == 0:
print(f"{number} 是偶数")
else:
print(f"{number} 是奇数")输出:
7 是奇数解释:
number % 2计算number除以2的余数- 如果余数为0,说明是偶数
- 如果余数不为0,说明是奇数
示例3:判断是否及格
score = 75
if score >= 60:
print("恭喜你,及格了!")
print("继续努力!")
else:
print("很遗憾,不及格")
print("需要继续努力学习")输出:
恭喜你,及格了!
继续努力!示例4:登录验证
username = "admin"
password = "123456"
correct_username = "admin"
correct_password = "123456"
if username == correct_username and password == correct_password:
print("登录成功!")
print(f"欢迎回来,{username}")
else:
print("登录失败!")
print("用户名或密码错误")多行代码块
if和else下面的代码块可以包含多行代码。
示例5:多行代码块
score = 85
if score >= 90:
print("优秀!")
print("你的成绩非常棒!")
print("继续保持!")
else:
print("还需要努力!")
print("加油!")
print("下次争取更好!")
print("程序结束")嵌套if-else语句
if-else语句可以嵌套使用,即在if或else的代码块中再使用if-else。
示例6:嵌套if-else
number = 15
if number > 0:
if number % 2 == 0:
print(f"{number} 是正偶数")
else:
print(f"{number} 是正奇数")
else:
if number == 0:
print("这个数字是零")
else:
print(f"{number} 是负数")输出:
15 是正奇数示例7:成绩分级
score = 75
if score >= 60:
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
else:
print("及格")
else:
print("不及格")输出:
及格条件表达式(三元运算符)
Python提供了一种简洁的方式来写简单的if-else语句,称为条件表达式或三元运算符。
语法
值1 if 条件 else 值2解释:
- 如果条件为True,返回值1
- 如果条件为False,返回值2
示例8:条件表达式
# 传统写法
age = 20
if age >= 18:
message = "成年"
else:
message = "未成年"
# 使用条件表达式
age = 20
message = "成年" if age >= 18 else "未成年"
print(message) # 输出:成年示例9:找出最大值
a = 10
b = 20
# 传统写法
if a > b:
max_value = a
else:
max_value = b
# 使用条件表达式
max_value = a if a > b else b
print(f"最大值是:{max_value}") # 输出:最大值是:20示例10:判断奇偶数
number = 7
result = "偶数" if number % 2 == 0 else "奇数"
print(f"{number} 是{result}") # 输出:7 是奇数实际应用案例
案例1:用户登录系统
def 登录验证(用户名, 密码):
正确用户名 = "admin"
正确密码 = "123456"
if 用户名 == 正确用户名 and 密码 == 正确密码:
return "登录成功"
else:
return "登录失败"
result = 登录验证("admin", "123456")
print(result) # 输出:登录成功案例2:温度转换建议
temperature = 25
if temperature >= 30:
advice = "天气很热,注意防暑降温!"
else:
advice = "天气适宜,可以外出活动!"
print(advice) # 输出:天气适宜,可以外出活动!案例3:购物折扣
total_amount = 1500
if total_amount >= 1000:
discount = 0.8 # 8折
else:
discount = 1.0 # 无折扣
final_price = total_amount * discount
print(f"折后价格:¥{final_price:.2f}") # 输出:折后价格:¥1200.00案例4:年龄判断
age = 15
if age < 6:
category = "学龄前儿童"
elif age < 12:
category = "小学生"
elif age < 18:
category = "中学生"
else:
category = "成年人"
print(f"{age}岁属于:{category}") # 输出:15岁属于:中学生案例5:闰年判断
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")输出:
2024年是闰年案例6:彩票抽奖
import random
lucky_number = 7
user_number = random.randint(1, 10) # 随机生成1-10的数字
if user_number == lucky_number:
print(f"恭喜!你中奖了!你的号码是{user_number},幸运号码是{lucky_number}")
else:
print(f"很遗憾,未中奖。你的号码是{user_number},幸运号码是{lucky_number}")案例7:用户权限检查
def 检查权限(角色):
if 角色 == "admin":
return "管理员权限:可以访问所有功能"
elif 角色 == "user":
return "普通用户权限:可以访问基础功能"
else:
return "访客权限:只能查看公开内容"
print(检查权限("admin")) # 输出:管理员权限:可以访问所有功能
print(检查权限("guest")) # 输出:访客权限:只能查看公开内容常见错误与注意事项
错误1:忘记else后的冒号
# 错误
score = 75
if score >= 60:
print("及格")
else # 忘记冒号
print("不及格")正确:
score = 75
if score >= 60:
print("及格")
else: # 添加冒号
print("不及格")错误2:else后面添加条件
# 错误:else后面不能添加条件
score = 75
if score >= 60:
print("及格")
else score >= 80: # 错误:else后面不能有条件
print("良好")正确:
# 使用elif
score = 75
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
else:
print("及格")错误3:缩进不一致
# 错误
score = 75
if score >= 60:
print("及格")
else:
print("不及格") # 错误:缩进不一致正确:
score = 75
if score >= 60:
print("及格")
else:
print("不及格") # 正确:缩进一致错误4:滥用if-else
# 不推荐:重复的条件判断
score = 75
if score >= 60:
print("及格")
else:
print("不及格")
if score < 60:
print("需要努力")
else:
print("继续加油")推荐:使用elif(下集讲解)
score = 75
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")if-else vs 多个if
场景:判断成绩等级
方法1:使用多个if
score = 85
if score >= 90:
print("优秀")
if score >= 80 and score < 90:
print("良好")
if score >= 60 and score < 80:
print("及格")
if score < 60:
print("不及格")缺点:所有条件都会被检查,效率低
方法2:使用if-elif-else(下集讲解)
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")优点:只执行第一个匹配的条件,效率高
本集小结
- if-else语句用于处理二选一的情况
- if块在条件为True时执行
- else块在条件为False时执行
- if和else的代码块只能执行其中一个
- 嵌套if-else可以实现更复杂的逻辑
- 条件表达式(三元运算符)可以简洁地写简单的if-else
- 语法:
值1 if 条件 else 值2 - else后面不能添加条件
- else后面必须有冒号
- 所有代码块的缩进必须一致
课后练习
练习1:基础if-else
编写程序,判断一个数字是正数还是负数(假设数字不为0)。
number = -5
# 你的代码在这里练习2:判断奇偶数
编写程序,判断一个数字是奇数还是偶数。
number = 15
# 你的代码在这里练习3:成绩及格判断
编写程序,判断成绩是否及格。
score = 75
# 你的代码在这里练习4:使用条件表达式
使用条件表达式找出两个数字中的较大值。
a = 20
b = 15
# 使用条件表达式练习5:闰年判断
编写程序,判断一个年份是否为闰年。
year = 2024
# 你的代码在这里练习6:用户登录
编写一个登录验证程序,要求用户输入用户名和密码。
# 提示用户输入
username = input("请输入用户名:")
password = input("请输入密码:")
# 验证:用户名admin,密码123456练习7:购物折扣
编写程序,根据购物金额计算折扣:
- 满1000元打8折
- 不满1000元不打折
total = 1500
# 计算折后价格下集预告
下一集我们将学习第13集:if-elif-else多条件判断。使用if-elif-else语句,我们可以处理多个条件的情况,实现多选一的逻辑。这是条件语句中最强大的形式!
敬请期待!