第5章:if语句(if Statements)
一、导读
1.1 本章学习目标
第5章介绍Python的条件判断语句。本章核心目标:
- 掌握条件测试:比较运算符和布尔表达式
- 熟练使用if-elif-else:多分支判断
- 理解布尔值:True和False,以及falsy值
- 学会在条件中使用列表操作:
in、not in - 掌握嵌套if语句:复杂条件的处理
1.2 为什么本章如此重要
条件判断是控制程序流程的基础。Python的条件语句语法简洁直观,但有一些独特的特性(如falsy值、链式比较),需要充分理解才能写出正确的代码。
1.3 核心问题引导
Python中哪些值是falsy?和JavaScript有什么不同?
is 和 == 有什么区别?
Python支持链式比较(如 a < b < c),这是怎么工作的?
条件判断中的短路求值是如何工作的?
二、核心概念详解
5.1 条件测试
python
# 比较运算符
age = 18
print(age >= 18) # True
print(age == 18) # True
print(age != 20) # True
print(age < 18) # False
# 链式比较
x = 5
print(1 < x < 10) # True(等价于 1 < x and x < 10)
print(1 < x < 3) # False
print(1 < x <= 5) # True
# 逻辑运算符
print(True and False) # False
print(True or False) # True
print(not True) # False
# 短路求值
age = 25
has_id = True
print(age >= 18 and has_id) # True
# in 运算符
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True5.2 if语句
python
# 基本if
age = 20
if age >= 18:
print("Adult")
# if-else
temperature = 35
if temperature > 30:
print("Hot!")
else:
print("Comfortable")
# if-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: {score}, Grade: {grade}")
# 多条件
age = 25
income = 50000
if age >= 18 and income >= 30000:
print("Eligible for loan")
# 嵌套if
has_ticket = True
age = 15
if has_ticket:
if age >= 18:
print("Welcome!")
else:
print("Must be 18+")
else:
print("Please buy a ticket")5.3 真值测试
python
# Falsy值(在条件判断中为False)
print(bool(False)) # False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False(空字符串)
print(bool([])) # False(空列表)
print(bool({})) # False(空字典)
print(bool(())) # False(空元组)
print(bool(None)) # False
# 其他所有值都是Truthy
print(bool(1)) # True
print(bool("hello")) # True
print(bool([1, 2])) # True
# 实际使用
name = ""
if not name:
print("Name is empty!")
items = []
if items:
print(f"Has {len(items)} items")
else:
print("No items")
# is vs ==
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True(值相等)
print(a is b) # False(不是同一个对象)
c = a
print(a is c) # True(同一个对象)
# 推荐用 is 比较 None
x = None
if x is None:
print("x is None")5.4 条件判断与列表
python
# 检查列表元素
toppings = ["mushrooms", "green peppers", "onions"]
if "mushrooms" in toppings:
print("Adding mushrooms")
if "pepperoni" not in toppings:
print("No pepperoni")
# 检查列表是否为空
if toppings:
for topping in toppings:
print(f"Adding {topping}")
else:
print("Plain pizza?")
# 多个列表比较
available = ["mushrooms", "olives", "peppers"]
requested = ["mushrooms", "garlic"]
for item in requested:
if item in available:
print(f"Adding {item}")
else:
print(f"Sorry, no {item}")三、实战案例
3.1 简单的评分系统
python
def calculate_grade(score):
if score < 0 or score > 100:
return "Invalid"
elif score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# 测试
scores = [95, 85, 75, 65, 55, -5, 105]
for s in scores:
print(f"Score: {s:3d} -> Grade: {calculate_grade(s)}")3.2 闰年判断
python
def is_leap_year(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
# 简化版
def is_leap_year_short(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
for year in [2000, 2004, 2100, 2023, 2024]:
print(f"{year}: {'Leap' if is_leap_year(year) else 'Not leap'}")四、本章小结
第5章介绍了Python的条件判断:比较运算符、if-elif-else、布尔值和falsy值、in运算符、is vs ==。Python的条件语句语法简洁,支持链式比较。
五、思考与练习
思考题
Python的falsy值和JavaScript的falsy值有什么不同?
什么时候应该用is而不是==?
链式比较a < b < c的求值顺序是什么?
条件表达式(三元运算符)x if condition else y如何使用?
编程练习
实现一个BMI计算器,根据BMI值输出体重分类。
编写一个石头剪刀布游戏。
实现一个简单的ATM密码验证系统。