Python快速学习——第7章:选择语句

0 阅读7分钟

第七章:选择语句

7.1 什么是选择语句?

选择语句就像 人生中的岔路口,根据不同的条件决定程序要走哪条路。它让程序具备了"思考"能力,能够根据不同情况做出不同的决策。

# 简单的选择语句示例
age = 18
if age >= 18:
    print("你已经成年了!")
else:
    print("你还未成年!")

7.2 基本的if语句

7.2.1 单个条件判断

最基本的if语句只检查一个条件:

# 语法格式
if 条件:
    # 条件为True时执行的代码# 示例
score = 85
if score >= 60:
    print("恭喜,你及格了!")

7.2.2 代码块的缩进

Python使用缩进来表示代码块,这是Python语法的重要特点:

# 正确的缩进
if True:
    print("这行属于if代码块")
    print("这行也属于if代码块")
print("这行不属于if代码块")
​
# 错误的缩进会导致语法错误
# if True:
# print("这行没有正确缩进")  # 会报错!

7.3 if-else语句

当条件不满足时,执行else部分的代码:

# 语法格式
if 条件:
    # 条件为True时执行的代码
else:
    # 条件为False时执行的代码# 示例
temperature = 25
if temperature > 30:
    print("天气很热,穿短袖吧!")
else:
    print("天气适中,穿长袖吧!")

7.4 if-elif-else语句

当有多个条件需要判断时,使用elif(else if的缩写):

# 语法格式
if 条件1:
    # 条件1为True时执行的代码
elif 条件2:
    # 条件2为True时执行的代码
elif 条件3:
    # 条件3为True时执行的代码
else:
    # 所有条件都为False时执行的代码# 示例:成绩等级判断
score = 85
if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 70:
    print("中等")
elif score >= 60:
    print("及格")
else:
    print("不及格")

7.5 嵌套的if语句

if语句中可以包含另一个if语句,形成嵌套结构:

# 嵌套if语句示例
age = 20
has_license = Trueif age >= 18:
    print("你已成年")
    if has_license:
        print("你可以开车")
    else:
        print("你需要考取驾照才能开车")
else:
    print("你还未成年,不能开车")

7.6 条件表达式

条件表达式也叫三元运算符,是if-else的简洁写法:

# 语法格式
变量 = 值1 if 条件 else2# 传统写法
score = 85
if score >= 60:
    result = "及格"
else:
    result = "不及格"# 使用条件表达式
result = "及格" if score >= 60 else "不及格"
print(result)  # 及格# 另一个例子
age = 20
status = "成年人" if age >= 18 else "未成年人"
print(status)  # 成年人

7.7 比较运算符

选择语句的核心是比较运算符,用于比较两个值:

运算符描述示例结果
==等于5 == 5True
!=不等于5 != 3True
>大于5 > 3True
<小于5 < 3False
>=大于等于5 >= 5True
<=小于等于5 <= 3False
# 比较运算符示例
a = 10
b = 20print(a == b)   # False
print(a != b)   # True
print(a > b)    # False
print(a < b)    # True
print(a >= 10)  # True
print(b <= 15)  # False

7.8 逻辑运算符

逻辑运算符用于组合多个条件:

运算符描述示例结果
and与(两个条件都为True)True and FalseFalse
or或(至少一个条件为True)True or FalseTrue
not非(反转条件)not TrueFalse
# 逻辑运算符示例
age = 25
has_license = True
has_car = False# and 运算符(两个条件都要满足)
if age >= 18 and has_license:
    print("你可以合法开车")
​
# or 运算符(至少满足一个条件)
if has_license or has_car:
    print("你可能有交通方式")
​
# not 运算符(反转条件)
if not has_car:
    print("你没有车")
​
# 复杂条件组合
if (age >= 18 and has_license) or has_car:
    print("你有交通出行的能力")

7.9 成员运算符

成员运算符用于检查序列中是否包含某个元素:

运算符描述示例结果
in如果在序列中找到值返回True"a" in "abc"True
not in如果在序列中没有找到值返回True"d" not in "abc"True
# 成员运算符示例
fruits = ["苹果", "香蕉", "橙子"]
​
# in 运算符
if "苹果" in fruits:
    print("有苹果")
​
# not in 运算符
if "葡萄" not in fruits:
    print("没有葡萄")
​
# 在字符串中使用
text = "Hello World"
if "Hello" in text:
    print("文本包含Hello")

7.10 身份运算符

身份运算符用于比较两个对象是否是同一个对象:

运算符描述示例结果
is如果两个变量是同一个对象则返回Truex is y相同对象为True,否则False
is not如果两个变量不是同一个对象则返回Truex is not y不同对象为True,否则False
# 身份运算符示例
a = [1, 2, 3]
b = [1, 2, 3]
c = a
​
print(a == b)   # True - 值相等
print(a is b)   # False - 不是同一个对象
print(a is c)   # True - 是同一个对象# 常用场景:检查是否为None
value = None
if value is None:
    print("值未设置")

7.11 选择语句的常见应用场景

7.11.1 用户输入验证

# 验证用户输入
username = input("请输入用户名:")
password = input("请输入密码:")
​
if username == "admin" and password == "123456":
    print("登录成功!")
else:
    print("用户名或密码错误!")

7.11.2 数值范围判断

# 判断成绩等级
score = int(input("请输入成绩:"))
​
if score < 0 or score > 100:
    print("成绩无效!")
elif score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 70:
    print("中等")
elif score >= 60:
    print("及格")
else:
    print("不及格")

7.11.3 菜单选择

# 简单的菜单系统
print("=== 菜单 ===")
print("1. 开始游戏")
print("2. 设置")
print("3. 退出")
​
choice = input("请选择:")
​
if choice == "1":
    print("开始游戏...")
elif choice == "2":
    print("进入设置...")
elif choice == "3":
    print("退出程序...")
else:
    print("无效选择!")

7.11.4 数据过滤

# 过滤数据
numbers = [12, 45, 78, 23, 56, 89, 34, 67]
​
# 找出所有大于50的数
large_numbers = []
for num in numbers:
    if num > 50:
        large_numbers.append(num)
​
print("大于50的数:", large_numbers)

7.12 选择语句的注意事项

7.12.1 避免常见的逻辑错误

# 错误:使用赋值运算符=而不是比较运算符==
age = 20
# if age = 18:  # 这会报错!
if age == 18:   # 正确
    print("刚好18岁")
​
# 错误:链式比较的写法
x = 5
# if 0 < x < 10:  # 这种写法在Python中实际上是正确的!
if x > 0 and x < 10:  # 更清晰的写法
    print("x在0到10之间")

7.12.2 使用elif避免不必要的检查

# 不好的写法 - 每个条件都会被检查
score = 85
if score >= 90:
    print("优秀")
if score >= 80:  # 这个条件也会被检查,即使已经知道score=85
    print("良好")
if score >= 70:  # 这个条件也会被检查
    print("中等")
​
# 好的写法 - 使用elif,找到匹配条件后就停止检查
if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")  # 执行这里后就停止检查
elif score >= 70:
    print("中等")  # 不会执行到这里

7.12.3 空代码块的处理

# 如果需要空代码块,使用pass
age = 15
if age >= 18:
    pass  # 什么也不做,但语法需要
else:
    print("你还未成年")
​
# 或者使用占位注释
if age >= 18:
    # TODO: 添加成年人逻辑
    pass

7.13 选择语句与布尔值

在Python中,很多值在条件判断中会被当作True或False:

以下情况被视为False:False, None, 0, 0.0, "", [], (), {}, set()

以下情况被视为True:True, 非零数字, 非空字符串, 非空列表, 非空元组, 非空字典, 非空集合

name = ""
if name:  # 空字符串被视为False
    print(f"你好,{name}")
else:
    print("请输入姓名")  # 会执行这里
​
numbers = [1, 2, 3]
if numbers:  # 非空列表被视为True
    print("列表中有数据")

本章笔记:

  • 选择语句让程序能够根据不同条件执行不同的代码。
  • if语句用于单个条件判断,if-else用于二选一,if-elif-else用于多条件判断。
  • Python使用缩进来表示代码块,这是语法的重要部分。
  • 比较运算符用于比较值,逻辑运算符用于组合多个条件。
  • 成员运算符检查序列中是否包含元素,身份运算符检查是否为同一对象。
  • 条件表达式是if-else的简洁写法。
  • 选择语句常用于用户输入验证、数值范围判断、菜单选择等场景。
  • 在Python中,很多值在条件判断中会被隐式转换为布尔值。