Python 训练 Day 11

mac2024-06-27  56

Python 训练 Day 11 else与with语句

静水流深 2019.10.31 今天我们学习一下 else 语句和 with 语句。

else语句

在python中的else语句非常的强大,他可以和很多语句配套使用。 if、循环语句、 异常处理 都是可以和他搭档的。

一、if 语句和 else 搭配

简单一句形容。要么怎样,否则怎样。 格式如下

if ture : ststement 1 else statement 2

就是说在 if 后的判断成立时,执行 statement 1 ,否则(也就是判断不成立)执行 tatement 2。

二、else 语句和循环语句搭配

else 执行条件: 循环里的语句执行完成 循环里的语句没有被 break 语句打断 格式如下

shuru = int(input ('输入一个数:')) count = shuru // 2 while count>1: if shuru % count ==0 : print('最大约数是;',count) break else : count -= 1 else : print('你输入的是素数。')

三、else 和异常处理搭配。

就是既然没问题,就这么干吧! 格式

try statements except statement 1 else statement 2

翻译一下,就是说在异常处理的 try 和 except 都不执行 的时候,执行 else 的语句 statement 2 。

with 语句

将文件关闭的问题抽象化,不需关注细节,with 自动调用f.close( ) 关闭该文件使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件。 格式如下

try f = open ('wenjian.txt','w') for eachline in f : print (eachline) except OSError as reason print('出错了。') finally f.close()

就等于

try with open ('wenjian.txt','w') as f . for eachline in f : print (eachline) except OSError as reason print('出错了。')
最新回复(0)