python中else与with语句(day9)

else语句

if-else语句

wwe = input("sname")
if wwe.endswith("wawa"):
    print("wwwe,wawa")
else:
    print("wwe,nono")

while-else语句(如有break,直接跳出,不执行else语句)

count = 0
while count < 5:
   print(count, " is  less than 5")
   count = count + 1
else:
   print(count, " is not less than 5")
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

for-else语句(与while-else语句用法相同)

with语句

使用with后不管with中的代码出现什么错误,都会进行对当前对象进行清理工作。

例如file的file.close()方法,无论with中出现任何错误,都会执行file.close()方法
with语句只用在支持上下文管理器的对象,而上下文管理器则是
这个管理器就是在对象内实现了两个方法:enter() 和__exit__()
enter()方法会在with的代码块执行之前执行,exit()会在代码块执行结束后执行。
exit()方法内会自带当前对象的清理方法。

with context_expression [as target(s)]:
with-body

with open(r'somefileName') as somefile:
        for line in somefile:
            print line
            # ...more code
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值