python基础之else语句和with语句

在python中else语句用处非常大,不像其他语言,else语句只用于和if搭配,python中的else语句打了激素,可以与if,while循环,for 循环,try语句搭配着使用。

if 条件:
    条件为真执行语句
else:
    条件为假执行语句
#即要么怎样,要么不怎样

while 条件:
    条件为真执行循环体
else:
    如果实现了循环并且没有break,执行语句

#即干完了能怎样,干不完就别想怎样

try:
    语句
except:
    语句
else:
    语句
#即没有问题,那就干吧


使用with语句避免文件打开忘记关闭的尴尬了,with会自动考虑文件关闭的问题


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

#以上可以用with语句写
try:
    with open('data.txt','w') as f:
        for eachline in f:
            print(eachline)
except  OSError as reason:
    print('出错了'+str(reason))

猜你喜欢

转载自blog.csdn.net/weixin_42920648/article/details/81735913