Python学习笔记9-else与with语句

本文最后更新于 将近 6 年前,文中所描述的信息可能已发生改变。

else与with语句

else

i=1
while i<=5:
    print(i)
    i+=1
else:
    print(i,">5")

1
2
3
4
5
6 >5
i=1
for i in range(1,11):
    print(i)
else:
    print("Else:",i)


1
2
3
4
5
6
7
8
9
10
Else: 10
Press any key to continue . . .
def try():
    try:
        pass
    except TypeError as reason:
        print("报错")
    else:
        print("到我这里了") #当try块中的语句正常执行完毕会执行该方法。

with

# 第一种写法
def withas():
    try:
        f = open("1.txt")
        print(f.read())
        f.close()
    except OSError as reason:
        print("读取错误")
    else:
        print("完成")
# 第二种写法 with,一定不要忘记  : 哦
def withas2():
    try:
        with open("文字.txt") as f:
            print(f.read())
            f.close()
    except OSError as reason:
        print("读取错误")
    else:
        print("完成")

打开一个文件的时候,可能这个文件并不存在,那么这个时候就会报错,而我们可能会使用try except finally这样的语句,并且在finally里边可能添加了f.close()这样的语句,但是我们这个时候并没有打开一个f的文件,因为这个文件并不存在,所以没有必要关闭这个文件。这时候我们就用到了with。

Python学习笔记8-异常处理
大学 梦起飞的地方