python极速入门之分支结构
if结构
单分支结构
计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。
比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现:
age = 20
if age >= 18:
print('your age is', age)
print('adult')
双分支结构
根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print语句执行了,否则,什么也不做。
也可以给if添加一个else语句,意思是,如果if判断是False,不要执行if的内容,去把else执行了:
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')
注意不要少写了冒号:。


分支嵌套结构
#方式一:判断的嵌套;
age=int(input('请输入你的年龄:'))
#TypeError: '<' not supported between instances of 'str' and 'int' input返回的字符串类型
if age <18: #数字判断
if age<0:
print('不符合条件')
else:
print('未成年人')
else:
if age<200:
print('成年人')
else:
print('超出碳基生命的极限!')
多分支结构
当然上面的判断是很粗略的,完全可以用elif做更细致的判断:
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
elif是else if的缩写,完全可以有多个elif,所以if语句的完整形式就是:
if <条件判断1>:
<执行1>
elif <条件判断2>:
<执行2>
elif <条件判断3>:
<执行3>
else:
<执行4>
if语句执行有个特点,它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elif和else,所以,请测试并解释为什么下面的程序打印的是teenager:
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
if判断条件还可以简写,比如写:
if x:
print('True')
只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
input函数
最后看一个有问题的条件判断。很多同学会用input()读取用户的输入,这样可以自己输入,程序运行得更有意思:
birth = input('birth: ')
if birth < 2000:
print('00前')
else:
print('00后')
输入1982,结果报错:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
这是因为input()返回的数据类型是str,str不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情:
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
再次运行,就可以得到正确地结果。但是,如果输入abc呢?又会得到一个错误信息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
原来int()函数发现一个字符串并不是合法的数字时就会报错,程序就退出了。
如何检查并捕获程序运行期的错误呢?后面的错误和调试会讲到。
练习
小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
• 低于18.5:过轻
• 18.5-25:正常
• 25-28:过重
• 28-32:肥胖
• 高于32:严重肥胖
# print('''
# ╔———————系统监控功能菜单————————╗
# │ 1 查看CPU使用率 │
# │ 2 查看内存使用率 │
# │ 3 查看网络接口收发数据量 │
# │ 0 退出系统 │
# ╚————————————————————————————╝
# ''')
模式匹配
当我们用if ... elif ... elif ... else ...判断时,会写很长一串代码,可读性较差。
如果要针对某个变量匹配若干种情况,可以使用match语句。
例如,某个学生的成绩只能是A、B、C,用if语句编写如下:
score = 'B'
if score == 'A':
print('score is A.')
elif score == 'B':
print('score is B.')
elif score == 'C':
print('score is C.')
else:
print('invalid score.')
如果用match语句改写,则改写如下:
score = 'B'
match score:
case 'A':
print('score is A.')
case 'B':
print('score is B.')
case 'C':
print('score is C.')
case _: # _表示匹配到其他任何情况
print('score is ???.')
使用match语句时,我们依次用case xxx匹配,并且可以在最后(且仅能在最后)加一个case _表示“任意值”,代码较if ... elif ... else ...更易读。
复杂匹配
match语句除了可以匹配简单的单个值外,还可以匹配多个值、匹配一定范围,并且把匹配后的值绑定到变量:
age = 15
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.')
在上面这个示例中,第一个case x if x < 10表示当age < 10成立时匹配,且赋值给变量x,第二个case 10仅匹配单个值,第三个case 11|12|...|18能匹配多个值,用|分隔。
可见,match语句的case匹配非常灵活。
匹配列表
match语句还可以匹配列表,功能非常强大。
我们假设用户输入了一个命令,用args = ['gcc', 'hello.c']存储,下面的代码演示了如何用match匹配来解析这个列表:
args = ['gcc', 'hello.c', 'world.c']
# args = ['clean']
# args = ['gcc']
match args:
# 如果仅出现gcc,报错:
case ['gcc']:
print('gcc: missing source file(s).')
# 出现gcc,且至少指定了一个文件:
case ['gcc', file1, *files]:
print('gcc compile: ' + file1 + ', ' + ', '.join(files))
# 仅出现clean:
case ['clean']:
print('clean')
case _:
print('invalid command.')
第一个case ['gcc']表示列表仅有'gcc'一个字符串,没有指定文件名,报错;
第二个case ['gcc', file1, *files]表示列表第一个字符串是'gcc',第二个字符串绑定到变量file1,后面的任意个字符串绑定到*files,它实际上表示至少指定一个文件;
第三个case ['clean']表示列表仅有'clean'一个字符串;
最后一个case _表示其他所有情况。
可见,match语句的匹配规则非常灵活,可以写出非常简洁的代码。
match status:
case 401|402|403|404:
return "Fail"
case 200:
return "Success"
- 点赞
- 收藏
- 关注作者
评论(0)