Python语法基础刻意练习:Task09(else与with语句)

mac2024-06-19  38

else的用法

1.if—else结构 最常见的的if—else语句:

num=int(input('please input a number which is not 0: ')) if num>0: print('+') else: print('-')

2.while—else 当while中有break时,可以用else判断是否执行了break:

num=int(input('please input a number: ')) temp=num-1 while temp>1: if num%temp==0: print('num is not a prime.') break temp=temp-1 else: print('num is a prima.')

3.try—except—else

# -*- coding: UTF-8 -*- try: fh = open("try3.py") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print ("Error: 没有找到文件或读取文件失败") else: print ("内容写入文件成功") fh.close()

with语句

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

try: with open('try3.py','w') as f: for eachline in f: print(eachline) except OSError as reason: print('出错啦:'+ str(reason)) #出错啦:not readable
最新回复(0)