else 与with 语句
 1.else 语句2.with 语句
 
  
 
1.else 语句
 
while - else 语句 
list1
=[x 
for x 
in range(0,100)]
i
,s
=0,0
while i
<100 :
    s
=list1
[i
]+s
    i
+=1
else:
    print('100以内的整数和是%d'%s
) 
 
 
for - else 语句 
s
=0
for i 
in range(0,100):
    s
+=i
else:
    print('100以内的整数和是%d'%s
) 
 
 
try -except - else 语句 
import random
try:
   n
=[random
.randint
(0,100)]
   m
=[random
.randint
(0,100)]
   x
=m
[0]/n
[0]
except ZeroDivisionError 
as z
:
   print('n是零')
else:
   print(x
) 
   
 
2.with 语句
 
with是一种上下文管理协议,常用于文件处理,可以简化try….except….finlally的处理流程。(文件打开后必须关闭,处理异常时往往需要finally 语句以关闭文件,而with 语句可以省略这一步) 
with expression 
[as target 
]:
 代码过程
try:
 with open('a.txt','w') as f
:
  for lines 
in f 
:
   print(lines
)
except OSError 
as o
:
 print(o
) 
                
                
                
        
    
 
                    转载请注明原文地址: https://mac.8miu.com/read-497713.html