计算机之所以能做很多自动化的任务,因为它可以自己做条件判断
在Python程序中,用if语句实现
if语句
if判断条件可以简写,比如
只要if后面的x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
if x:
print('True')
if语句执行有个特点,它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elif和else
案例如下:
def ad_age(age):
print('第一种')
if age >= 6:
print('teenager')
elif age >= 18: # elif是else if的缩写,可以有多个elif
print('adult')
else:
print('kid')
print('第二种')
if age >= 18:
print('adult')
elif age >= 6: # elif是else if的缩写,可以有多个elif
print('teenager')
else:
print('kid')
print('\n')
print('输入年龄4时')
ad_age(4)
print('输入年龄15时')
ad_age(15)
print('输入年龄25时')
ad_age(25)

在【输入年龄25时】可以明显的看出两个方式输出的差异
match语句
当我们用if ... elif ... elif ... else ...判断时,会写很长一串代码,可读性较差。如果要针对某个变量匹配若干种情况,可以使用match语句(需要Python 3.10及以上)
score = 'A'
# if语句
if score == 'A':
print('score is A.')
elif score == 'B':
print('score is B.')
elif score == 'C':
print('score is C.')
elif score == 'D':
print('score is D.')
else:
print('invalid score.')
# match语句(需要Python 3.10及以上)
match score:
case 'A':
print('score is A.')
case 'B':
print('score is B.')
case 'C':
print('score is C.')
case 'D':
print('score is D.')
case _: # _表示匹配到其他任何情况
print('score is ???.')
上面的语句运行结果输出是一样的
match语句除了可以匹配简单的单个值外,还可以匹配多个值、匹配一定范围,并且把匹配后的值绑定到变量
age = 25
match age:
case x if x < 10:
print(f'< 10 years old: {x}')
case 10:
print('10 years old.')
case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18:
print('11~18 years old.')
case 19:
print('19 years old.')
case _:
print('not sure.')
1.第一个case x if x < 10表示当age < 10成立时匹配,且赋值给变量x
2.第二个case 10仅匹配单个值
3.第三个case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18能匹配多个值,用|分隔
match语句的case匹配非常灵活(我python版本3.8,运行会报错)
Python中if和match语句的条件判断
572

被折叠的 条评论
为什么被折叠?



