首页 文章

python中的ValueError和TypeError

提问于
浏览
5

我无法完全理解Python3x中Type和Value错误之间的区别 .

当我尝试使用float('string')而不是TypeError时,为什么会得到ValueError?不应该给出一个TypeError因为我传递一个'str'类型的变量要转换成float?

In [169]: float('string')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-169-f894e176bff2> in <module>()
----> 1 float('string')

ValueError: could not convert string to float: 'string'

1 回答

  • 9

    值错误是

    当内置操作或函数接收到具有正确类型但值不合适的参数时引发

    float 函数可以带一个字符串,即 float('5') ,只是 float('string') 中的值 'string' 是一个不合适的(不可兑换的)字符串

    另一方面,

    传递错误类型的参数(例如,在期望int时传递列表)应该导致TypeError

    因此,如果您尝试使用 float(['5']) ,则会得到 TypeError 因为列表永远不能转换为浮点数 .

    Cite

相关问题