龙空技术网

Python数据分析笔记#4 错误和异常处理

Yuan的学习笔记 1161

前言:

今天姐妹们对“python画图报错”大体比较着重,看官们都需要了解一些“python画图报错”的相关文章。那么小编同时在网摘上汇集了一些关于“python画图报错””的相关内容,希望小伙伴们能喜欢,各位老铁们一起来学习一下吧!

错误和异常处理

我们写程序时常常会遇到各种错误,比如下面一个例子,当把一个字符串转化为浮点数类型时,程序就会报错:

In [1]: float('1.2345')Out[1]: 1.2345In [2]: float('something')---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-2-2649e4ade0e6> in <module>----> 1 float('something')ValueError: could not convert string to float: 'something'

最下面的ValueError告诉你,不能把字符串转化为浮点数。

当有用户使用我们编写的程序时可能因为某些原因(比如不小心或不会用)导致了程序出错,我们可能需要更优雅的处理这些错误。

比如我们可以写一个函数:

def attempt_float(x):    try:        return float(x)    except:        print('could not convert string to float')                                                                        return x

当float(x)出异常的时候,会执行下面except的部分:

In [4]: attempt_float('1.2345')Out[4]: 1.2345In [5]: attempt_float('something')could not convert string to floatOut[5]: 'something'

若我们输入了一个元组进去:

In [6]: float((1, 2))---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-6-82f777b0e564> in <module>----> 1 float((1, 2))TypeError: float() argument must be a string or a number, not 'tuple'

我们可以看到这次抛出的异常不是ValueError而是TypeError(类型错误),我们可以只处理ValueError的错误:

def attempt_float(x):    try:        return float(x)    except ValueError:        print('could not convert string to float')                                                                        return x

当要把'banana'转化为浮点数时(ValueError):

In [9]: attempt_float('banana')could not convert string to floatOut[9]: 'banana'

当要把元组转化为浮点数时(TypeError):

In [10]: attempt_float((1,2))---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-10-102527222085> in <module>----> 1 attempt_float((1,2))<ipython-input-8-3ff52c4ecd95> in attempt_float(x)      1 def attempt_float(x):      2     try:----> 3         return float(x)      4     except ValueError:      5         print('could not convert string to float')TypeError: float() argument must be a string or a number, not 'tuple'

我们也可以用元组包含多个异常:

def attempt_float(x):    try:        return float(x)    except (ValueError, TypeError):                                                                       return x

标签: #python画图报错