最典型的多分支
score = 85
if score >= 90:
level = '优秀'
elif score >= 60:
level = '及格'
else:
level = '不及格'
print(level)
嵌套判断
age = 20
if age >= 18:
if age >= 60:
print('老年票')
else:
print('成人票')
else:
print('儿童票')
三元表达式
status = '通过' if score >= 60 else '未通过'
本站补充:match 语句
Python 3.10 起可以用 match 做模式匹配,多值分支比一长串 elif 更清楚:
match score // 10:
case 10 | 9:
print('A')
case 8:
print('B')
case _:
print('继续加油')本文根据 W3School Python 教程 的知识点重新整理、补充示例编写,非原文转载。