导航菜单

Python 编程/控制流程
课程进度 30% · 第4/11章4/11章 · 标签 1/4
1

if-elif-else 语句

Python使用缩进来组织代码块,条件语句遵循简洁的语法。

python
1
# 基本的if语句
2
x = 10
3
if x > 0:
4
print("x是正数")
5
 
6
# if-else语句
7
y = -5
8
if y > 0:
9
print("y是正数")
10
else:
11
print("y是负数或零")
12
 
13
# if-elif-else语句
14
score = 85
15
if score >= 90:
16
grade = "A"
17
elif score >= 80:
18
grade = "B"
19
elif score >= 70:
20
grade = "C"
21
elif score >= 60:
22
grade = "D"
23
else:
24
grade = "F"
25
print(f"成绩: {grade}") # 成绩: B
26
 
27
# 嵌套条件
28
num = 15
29
if num > 0:
30
if num % 2 == 0:
31
print("正偶数")
32
else:
33
print("正奇数")
34
else:
35
if num < 0:
36
print("负数")
37
else:
38
print("零")
2

三元表达式与 match-case

python
1
# 三元表达式
2
x = 10
3
result = "正数" if x > 0 else "负数或零"
4
print(result) # 正数
5
 
6
# match-case(Python 3.10+)
7
def describe_value(value):
8
match value:
9
case 0:
10
return "零"
11
case 1 | 2 | 3:
12
return "小数字"
13
case int() as n if n < 0:
14
return f"负数: {n}"
15
case int():
16
return f"正整数: {value}"
17
case str():
18
return f"字符串: {value}"
19
case _:
20
return "其他类型"
21
 
22
print(describe_value(0)) # 零
23
print(describe_value(5)) # 正整数: 5
24
print(describe_value(-3)) # 负数: -3
25
print(describe_value("hi")) # 字符串: hi

📖Python 3.10+ 支持 match-case 模式匹配,类似于其他语言的 switch-case。条件表达式(三元运算符)可以简化简单的分支