一、前 言
Python中条件判断没什么好讲的,有部分注意关注的点在下面带一下:
二、语法
- if、elif、else语法从上往下执行,如果某处判断为True,则后面语句就不会执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| numbers = [11, 21, 31, 41, 51, 61, 71, 81, 91, 101]
for number in numbers: if number > 71: print(f"{number} 大于 71") elif number > 51: print(f"{number} 大于 51,但不大于 71") else: print(f"{number} 不大于 51")
height = 1.75 weight = 80.5 bmi = weight / height**2
if bmi < 18.5: result = "过轻" elif bmi < 25: result = "正常" elif bmi < 28: result = "过重" elif bmi < 32: result = "肥胖" else: result = "严重肥胖"
print(f"BMI: {bmi:.1f},体重状态:{result}")
|
match、case 是 Python 3.10 引入的结构化模式匹配。它不只是传统的 switch,还可以解构列表等复合数据:
1 2 3 4 5 6 7 8 9
| command = ["move", 10, 20]
match command: case ["move", x, y]: print(f"移动到坐标 ({x}, {y})") case ["quit"]: print("退出") case _: print("未知命令")
|