条件语句,即通过判断条件是否成立,根据条件表达式的结果,控制不同代码块的执行。
目录
3. match...case (Python 3.10+)
1. if 语句
if 语句是Python中最基本的条件控制结构,用于根据条件执行不同的代码块。
基本语法
if 条件表达式:
# 条件为真时执行的代码
age = 18
if age >= 18:
print("您已成年,可以进入")
条件表达式常用的运算符
分类
|
运算符
|
操作符含义
|
算术运算符
| + |
加法
|
- |
减法
| |
* |
乘法
| |
/ |
除法,结果为浮点数
| |
// |
除法,结果为向下取整的整数
| |
% |
取模
/
求余
| |
** |
幂运算
| |
关系运算符
| = |
等于
|
!= |
不等于
| |
> |
大于
| |
< |
小于
| |
>= |
大于或等于
| |
<= |
小于或等于
| |
成员运算符
|
in
|
存在
/
属于
|
not in |
不存在
/
不属于
|
if-else 结构
if age >= 18:
print("您已成年,可以进入")
else:
print("您未成年,禁止进入")
if-elif-else 结构
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
2. if 嵌套
可以在一个if语句中嵌套另一个if语句,实现更复杂的条件判断。
age = 20
has_id = True
if age >= 18:
if has_id:
print("验证通过,可以进入")
else:
print("请出示身份证")
else:
print("未成年人禁止进入")
多层嵌套示例
temperature = 28
humidity = 70
if temperature > 30:
if humidity > 80:
print("天气炎热且潮湿")
else:
print("天气炎热但干燥")
elif temperature > 20:
if humidity > 80:
print("天气温暖且潮湿")
else:
print("天气温暖舒适")
else:
print("天气凉爽")
3. match...case (Python 3.10+)
Python 3.10引入了match-case语句,类似于其他语言中的switch-case结构,但功能更强大。
基本语法
match 值:
case 模式1:
# 匹配模式1时执行的代码
case 模式2:
# 匹配模式2时执行的代码
case _:
# 默认情况
status = 404
match status:
case 200:
print("请求成功")
case 404:
print("页面未找到")
case 500:
print("服务器错误")
case _:
print("未知状态码")
复杂模式匹配
point = (3, 4)
match point:
case (0, 0):
print("原点")
case (0, y):
print(f"Y轴上,y坐标为{y}")
case (x, 0):
print(f"X轴上,x坐标为{x}")
case (x, y):
print(f"点位于({x}, {y})")
case _:
print("不是二维点")
4. 实验例程
例程1: 成绩评级
score = float(input("请输入成绩: "))
if score < 0 or score > 100:
print("成绩无效")
elif score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("E")
例程2: 闰年判断
year = int(input("请输入年份: "))
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")
例程3: 计算器(使用match-case)
num1 = float(input("请输入第一个数字: "))
operator = input("请输入运算符(+, -, *, /): ")
num2 = float(input("请输入第二个数字: "))
match operator:
case "+":
print(f"结果: {num1 + num2}")
case "-":
print(f"结果: {num1 - num2}")
case "*":
print(f"结果: {num1 * num2}")
case "/":
if num2 == 0:
print("错误: 除数不能为零")
else:
print(f"结果: {num1 / num2}")
case _:
print("无效的运算符")
例程4: 用户登录验证
username = input("用户名: ")
password = input("密码: ")
if username == "admin":
if password == "123456":
print("管理员登录成功")
else:
print("管理员密码错误")
else:
if password == "guest":
print("访客登录成功")
else:
print("用户名或密码错误")
这些条件控制结构是Python编程的基础,掌握它们对于编写逻辑清晰的代码至关重要。if语句适合简单的条件判断,嵌套if可以处理更复杂的条件逻辑,而match-case则为多条件分支提供了更简洁的语法。