目录
一、if 语句
Conditionals Make Decisions
if 语句流程
举个例子
def f(x):
print("A", end="")
if x == 0:
print("B", end=" ")
print("C", end=" ")
print("D")
f(1)
AD
一个更有意思的例子:
二丶if-else 语句
def f(x):
print("A", end="")
if x == 0:
print("B", end="")
print("C", end="")
else:
print("D", end="")
if x == 1:
print("E", end="")
else:
print("F", end="")
print("G")
f(1)
ADEG
三丶if-elif-else 语句
四丶match...case
Python 3.10 增加了 match...case 的条件判断。
match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard>
case _: 类似于 C 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。
总结
- Conditionals Make Decisions.
- if-else 结构构成了 Python 分支控制,if 还能嵌套使用。