2025-05-13 学习记录--Python-条件判断:if语句 + if-else语句 + if-elif-else语句 + match语句
合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。💪🏻
一、条件判断 ⭐️
(一)、if
语句 🍭
if 要判断的条件:条件成立时,要做的事情......
举例: 🌰
weather = '下雨'
if weather == '下雨':print('带伞出门') # if语句的下级代码
(二)、if-else
语句 🍭
if 要判断的条件:条件成立时,要做的事情......
else:条件不成立时,要做的事情......
举例1: 🌰
weather = '下雨'
if weather == '下雨':print('带伞出门')
else:print('不带伞出门')
举例2: 🌰
# 判断年龄
age = int(input('请输入你的年龄:'))
if age >= 18:print('可以去网吧')
else:print('在家写作业吧')
(三)、if-elif-else
语句 🍭
if 条件1:条件1满足执行的代码......
elif 条件2:条件2满足时,执行的代码......
elif 条件3:条件3满足时,执行的代码......
else:以上条件都不满足时,执行的代码......
举例: 🌰
score = 34
if score > 90:print('A')
elif score > 80:print('B')
elif score > 70:print('C')
else:print('D')
(四)、match
语句 🍭
举例1: 🌰
x = 10match x:case 1:print("x is 1")case 2:print("x is 2")case _: # 匹配所有其他值print("x is not 1 or 2")
举例2: 🌰
text = "hello"match text:case "hello":print("text is 'hello'")case "world":print("text is 'world'")case _:print("text is neither 'hello' nor 'world'")
(五)、举例 🌰
age = input('请输入你的年龄:')
if age.isdigit():age = int(age)if age >= 0 and age <= 120:print('输入正确')else:print('输入错误,请重新输入')
else:print('请输入阿拉伯数字!')