第5章 · if语句

编写条件测试,使用if-elif-else结构做出判断,并学会用if语句处理列表。

知识点 代码示例 章节测验(2 题)

知识点讲解

条件测试

if语句的核心是条件测试——一个表达式的值为True或False。比较运算符包括 ==(相等)、!=(不等)、><>=<=。检查列表是否包含某元素用 in,不含用 not in。布尔表达式可用 andor 组合。

if-elif-else结构

Python依次检查每个条件,遇到第一个为True的条件就执行其代码块并跳过其余分支。可以用任意数量的 elifelse 用于处理不满足任何条件的情况。测试多个独立条件时,应使用多个独立的if语句而非if-elif-else。

使用if处理列表

if语句常与列表配合使用:检查列表是否为空(if list:)、在循环中判断元素、确保列表非空后再遍历等。例如:

requested = ["mushrooms", "green peppers"]
if "mushrooms" in requested:
print("加蘑菇")

代码示例

if-elif-else

演示条件判断结构。

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 10
else:
    price = 20
print(f"票价 {price} 元")

requested_toppings = ["mushrooms", "green peppers", "cheese"]
for topping in requested_toppings:
    if topping == "green peppers":
        print("抱歉,青椒没有了")
    else:
        print(f"添加 {topping}")

用if处理列表

演示列表非空检查与包含判断。

requested_toppings = []
if requested_toppings:
    print("有配料")
else:
    print("没有配料,来份原味披萨")

available = ["mushrooms", "olives", "pepperoni"]
requested = ["mushrooms", "pineapple"]
for item in requested:
    if item in available:
        print(f"可以加 {item}")
    else:
        print(f"抱歉,没有 {item}")