python学习else,with

else

要么怎样,要么不怎样

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

if XXX:

  XXX

else:

  XXX

 1 def showMaxFactor(num):
 2     count = num // 2
 3     while count > 1:
 4         if num % count == 0:
 5             print('%d最大的约数是%d' % (num,count))
 6             break
 7         count -= 1
 8     else:
 9         print('%d是素数' % num)
10 
11 num = int(input('请输入一个数'))
12 showMaxFactor(num)

没有问题,那就干吧

try:
    int('abc')
except ValueError as reason:
    print('出错')
else:
    print('没错')

with

不使用with时

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

使用with时,会在异常时自动关闭文件f.close

try:
   with open('data.txt','w') as f
       for each_line in f:
           print(each_line)
except OSError as reason:
    print('出错'+ str(reason))
原文地址:https://www.cnblogs.com/jdzhang1995/p/10261083.html