python基础语法刻意练习——task9.else与with语句
else用法
Python中else除了可以与if组成条件语句外,还可以和while 、for 、try一起串联使用。 例:
else和while配合使用:
count
=0
while count
>12:
if (11>0):
print("成立")
break
count
+=1
else:
print('不成立')
else和for配合使用:
def forelse():
c
= [1,2]
for i
in c
:
print(i
)
else:
print("输出")
else和try配合使用:
def tryelse():
try:
sum = 1+1
except TypeError
as e
:
print("报错")
else:
print("到我这里了")
with语句
使用 with 语句处理文件对象,它会在文件用完后会自动关闭,就算发生异常也没关系。它是 try-finally 块的简写:
>>> with open('sample.txt') as fobj:
... for line in fobj:
... print(line, end = '')
...
I love Python
I love shiyanlou