【问题标题】:ValueError and TypeError in pythonpython中的ValueError和TypeError
【发布时间】:2018-06-28 19:54:42
【问题描述】:

我无法完全理解 Python3x 中类型和值错误之间的区别。

当我尝试使用 float('string') 而不是 TypeError 时,为什么会得到 ValueError?这不应该也给出一个 TypeError,因为我正在传递一个“str”类型的变量以转换为浮点数吗?

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'

【问题讨论】:

  • 部分字符串可以转成float,例如123
  • 字符串 ('string') 的 有问题,因为它不能转换为浮点数。
  • 另一个有效的例子是float("infinity")
  • 另一个是float("nan")

标签: python typeerror valueerror


【解决方案1】:

一个值错误是

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

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

另一方面,

传递错误类型的参数(例如,当需要一个 int 时传递一个列表)应该会导致 TypeError

因此,如果您尝试使用 float(['5']),您将获得 TypeError,因为列表永远无法转换为浮点数。

Cite

【讨论】:

    【解决方案2】:

    ValueError 函数被正确类型的值调用,但值不合适

    TypeError : 对不适当类型的值调用函数

    【讨论】:

      【解决方案3】:

      只想在大卫的回答中再补充一点。

      当我们向函数传递不正确的参数时,也会发生 TypeError。

      例如:

      def hello(int x,int y):
          pass
      
      hello(12)
      

      这也会给你类型错误:

      hello() 缺少 1 个必需的位置参数:'y'

      【讨论】:

        【解决方案4】:

        它们在 Python Documentation.

        我会为他们添加示例:

        类型错误:

        10 + 'a'
        

        值错误:

        int("hello")
        

        【讨论】:

          猜你喜欢
          • 2013-08-23
          • 1970-01-01
          • 2021-09-10
          • 1970-01-01
          • 2019-07-02
          • 1970-01-01
          • 2014-12-20
          • 1970-01-01
          • 2021-01-21
          相关资源
          最近更新 更多