Python报错不要慌,这三个关键词帮你解决问题!


全文共1983字,预计学习时长5分钟

图源:unsplash

 

写代码必然会出现错误,而错误处理可以针对这些错误提前做好准备。通常出现错误时,脚本会停止运行,而有了错误处理,脚本就可以继续运行。为此,我们需要了解下面三个关键词:

 

·        try:这是要运行的代码块,可能会产生错误。

·        except:如果在try块中出现错误,将执行这段代码。

·        finally:不管出现什么错误,都要执行这段代码。

 

现在,我们定义一个函数“summation”,将两个数字相加。该函数运行正常。

>>> defsummation(num1,num2):        print(num1+num2)>>>summation(2,3)5

接下来,我们让用户输入其中一个数字,并运行该函数。

 

>>> num1 = 2>>> num2 = input("Enter number: ")Enter number: 3>>> summation(num1,num2)>>> print("Thisline will not be printed because of the error")---------------------------------------------------------------------------TypeError                                Traceback (most recent call last)<ipython-input-6-2cc0289b921e> in <module>----> 1 summation(num1,num2)      2 print("This line will notbe printed because of the error")
<ipython-input-1-970d26ae8592> in summation(num1, num2)      1 def summation(num1,num2):----> 2     print(num1+num2)
TypeError: unsupported operand type(s) for +:  int  and  str 

“TypeError”错误出现了,因为我们试图将数字和字符串相加。请注意,错误出现后,后面的代码便不再执行。所以我们要用到上面提到的关键词,确保即使出错,脚本依旧运行。

 

>>> try:        summed = 2 +  3     except:        print("Summation is not ofthe same type")Summation is not of the same type

可以看到,try块出现错误,except块的代码开始运行,并打印语句。接下来加入“else”块,来应对没有错误出现的情况。

 

>>> try:        summed = 2 + 3    except:        print("Summation is not ofthe same type")    else:        print("There was no errorand result is: ",summed)There was no error and result is:  5

 

接下来我们用另外一个例子理解。这个例子中,在except块我们还标明了错误类型。如果没有标明错误类型,出现一切异常都会执行except块。

 

>>> try:        f = open( test , w )        f.write("This is a testfile")    except TypeError:        print("There is a typeerror")    except OSError:        print("There is an OSerror")    finally:        print("This will print evenif no error")This will print even if no error

 

现在,故意创造一个错误,看看except块是否与finally块共同工作吧!

 

>>> try:        f = open( test , r )        f.write("This is a testfile")    except TypeError:        print("There is a typeerror")    except OSError:        print("There is an OSerror")    finally:        print("This will print evenif no error")There is an OS errorThis will print even if no error


推荐阅读专题

留言点赞发个朋友圈

我们一起分享AI学习与发展的干货

编译组:李紫瑶、邓逸瑶

相关链接:

https://levelup.gitconnected.com/errors-and-exception-handling-in-python-e3560a879119

如转载,请后台留言,遵守转载规范

推荐文章阅读

ACL2018论文集50篇解读

EMNLP2017论文集28篇论文解读

2018年AI三大顶会中国学术成果全链接

ACL2017论文集:34篇解读干货全在这里

10篇AAAI2017经典论文回顾

长按识别二维码可添加关注

读芯君爱你

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值