Python:else与with语句

mac2026-03-15  3

python else与with语句

else语句

while···else 用于在while循环判定为False时,跳出循环并执行,注意下方进行比较,如果break跳出,则不会执行:

count=0; while count<5; print("%d is less than 5" % count) count=count+1 else: print("%d is not less than 5" % count)

for···else for中的语句和普通的没有区别,else中的语句会在循环正常执行完(即for不是通过break跳出而中断的)的情况下执行:

for num in range(10,20): for i in range(2,num): if num % 1 == 0: j=num/i print('%d 等于 %d * %d' % (num,i,j)) break else: print(num,'是一个质数')

try···except···else 如果在try子句执行时没有发生异常,python将执行else语句后面的语句(如果有else的话),然后控制流通过整个try语句:

try: a=1 print(b) except: pass else: print(1)

with语句

with open('myfile.txt','w') as f:

实现文件自动保存关闭,不需要主动close() 两种方法:

f=open('myfile.txt','w') for line in f: print(line) spt OSError as error: print('出错了!%s' % str(error)) ally: f.close() try: with open('myfile.txt','w') for lin in f: print(line) except OSError as error: print('出错了!%s' % str(error))
最新回复(0)