如何解决Python报错

这篇文章主要介绍“如何解决Python报错”,在日常操作中,相信很多人在如何解决Python报错问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何解决Python报错”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

我们提供的服务有:成都网站制作、网站建设、外贸网站建设、微信公众号开发、网站优化、网站认证、新华ssl等。为上千企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的新华网站制作公司

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

  • 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 error This will print even if no error

到此,关于“如何解决Python报错”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!

网站栏目:如何解决Python报错
网站地址:https://www.cdcxhl.com/article34/gihjse.html

成都网站建设公司_创新互联,为您提供Google云服务器网站收录网页设计公司面包屑导航网站营销

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站建设网站维护公司