Python 程序结构与条件语句

4.1 代码块与缩进

Python 使用缩进来定义代码块,而不是大括号 {}。这是 Python 最显著的特征之一。

缩进规则

  • 通常使用 4 个空格作为一级缩进
  • 同一代码块必须保持相同的缩进
  • 不要混用 Tab 和空格
1
2
3
4
5
6
7
8
9
# 正确的缩进
if True:
print("条件为真")
print("这是同一代码块")

# 错误的缩进(会报错)
# if True:
# print("第一行")
# print("缩进不一致") # IndentationError

4.2 if 语句

最基本的条件语句,用于根据条件执行不同的代码。

基本语法

1
2
3
if 条件:
# 条件为 True 时执行
代码块

示例

1
2
3
4
5
6
7
age = 18

if age >= 18:
print("已成年")
print("可以进入网吧")

print("程序继续执行")

4.3 if-else 语句

用于在条件为真和为假时分别执行不同的代码。

1
2
3
4
5
6
if 条件:
# 条件为 True 时执行
代码块 1
else:
# 条件为 False 时执行
代码块 2

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
score = 75

if score >= 60:
print("及格")
else:
print("不及格")

# 判断奇偶数
number = 7
if number % 2 == 0:
print(f"{number} 是偶数")
else:
print(f"{number} 是奇数")

4.4 if-elif-else 语句

用于处理多个条件的情况。

1
2
3
4
5
6
7
8
if 条件 1:
代码块 1
elif 条件 2:
代码块 2
elif 条件 3:
代码块 3
else:
默认代码块

示例:成绩等级判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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"成绩等级: {grade}") # 输出: B

示例:季节判断

1
2
3
4
5
6
7
8
9
10
11
12
month = 7

if month in [3, 4, 5]:
season = "春季"
elif month in [6, 7, 8]:
season = "夏季"
elif month in [9, 10, 11]:
season = "秋季"
else:
season = "冬季"

print(f"{month}月是{season}") # 输出: 7月是夏季

4.5 嵌套条件语句

条件语句可以嵌套使用。

1
2
3
4
5
6
7
8
9
10
age = 20
has_ticket = True

if has_ticket:
if age >= 18:
print("可以入场")
else:
print("未成年人需要家长陪同")
else:
print("请先购票")

示例:登录验证

1
2
3
4
5
6
7
8
9
10
username = "admin"
password = "123456"

if username == "admin":
if password == "123456":
print("登录成功")
else:
print("密码错误")
else:
print("用户名不存在")

4.6 三元表达式

Python 提供了一种简洁的条件表达式写法。

语法

1
1 if 条件 else2

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
age = 20

# 传统写法
if age >= 18:
status = "成年"
else:
status = "未成年"

# 三元表达式(等价写法)
status = "成年" if age >= 18 else "未成年"
print(status) # 成年

# 更多例子
x = 10
y = 20
max_value = x if x > y else y
print(f"较大值是: {max_value}") # 20

# 判断正负
num = -5
result = "正数" if num > 0 else ("负数" if num < 0 else "零")
print(result) # 负数

4.7 match-case 语句

Python 3.10+ 引入了结构模式匹配(类似其他语言的 switch-case)。

基本语法

1
2
3
4
5
6
7
match 表达式:
case 模式 1:
代码块 1
case 模式 2:
代码块 2
case _:
默认代码块

示例:星期判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
day = 3

match day:
case 1:
print("星期一")
case 2:
print("星期二")
case 3:
print("星期三")
case 4:
print("星期四")
case 5:
print("星期五")
case 6:
print("星期六")
case 7:
print("星期日")
case _:
print("无效的日期")

示例:HTTP 状态码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
status_code = 404

match status_code:
case 200:
print("请求成功")
case 301 | 302:
print("重定向")
case 400:
print("请求错误")
case 404:
print("未找到")
case 500:
print("服务器错误")
case _:
print("未知状态码")

4.8 条件语句最佳实践

1. 避免过度嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 不推荐:嵌套过深
if user:
if user.is_active:
if user.has_permission:
print("允许访问")

# 推荐:提前返回(卫语句)
if not user:
return
if not user.is_active:
return
if not user.has_permission:
return
print("允许访问")

2. 使用 in 简化条件

1
2
3
4
5
6
7
# 不推荐
if day == 1 or day == 2 or day == 3 or day == 4 or day == 5:
print("工作日")

# 推荐
if day in [1, 2, 3, 4, 5]:
print("工作日")

3. 利用真值测试

1
2
3
4
5
6
7
8
9
10
11
name = ""

# 不推荐
if len(name) == 0:
print("名字为空")

# 推荐
if not name:
print("名字为空")

# 常见假值:None, False, 0, "", [], {}, set()

4.9 本章小结

  • Python 使用缩进定义代码块,通常 4 个空格
  • if 用于单条件,if-else 用于双条件,if-elif-else 用于多条件
  • 三元表达式:值 1 if 条件 else 值 2
  • Python 3.10+ 支持 match-case 结构模式匹配
  • 避免过度嵌套,使用卫语句提前返回
  • 利用 in 和真值测试简化代码

练习题

  1. 编写程序:输入一个年份,判断是否为闰年(能被 4 整除但不能被 100 整除,或能被 400 整除)
  2. 编写程序:输入三个数,输出最大值
  3. 编写程序:根据输入的分数输出等级(A: 90+, B: 80-89, C: 70-79, D: 60-69, F: <60)
  4. 以下代码输出什么?
    1
    2
    3
    4
    5
    6
    7
    x = 10
    if x > 5:
    print("A")
    elif x > 8:
    print("B")
    else:
    print("C")
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Python基础教程 系列
第 4/20 篇
分享: