码迷,mamicode.com
首页 > 编程语言 > 详细

python学习else,with

时间:2019-01-12 22:59:36      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:素数   line   err   class   color   try   actor   code   最大的   

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))

 

python学习else,with

标签:素数   line   err   class   color   try   actor   code   最大的   

原文地址:https://www.cnblogs.com/jdzhang1995/p/10261083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!