代码之家  ›  专栏  ›  技术社区  ›  thileepan

python中的ValueError和TypeError

  •  24
  • thileepan  · 技术社区  · 8 年前

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

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

    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'
    
    4 回复  |  直到 8 年前
        1
  •  45
  •   David    8 年前

    值错误为

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

    这个 float 函数可以接受字符串,即 float('5') ,只是 'string' 在里面 float('string') 是不合适的(不可转换)字符串

    另一方面

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

    所以你会得到 TypeError 如果你试过 float(['5']) 因为列表永远无法转换为浮点。

    Cite

        2
  •  3
  •   Imad77    6 年前

    ValueError对正确类型的值调用函数,但值不正确

    TypeError:对类型不正确的值调用函数

        3
  •  2
  •   Szabolcs Dombi    4 年前

    他们在 Python Documentation .

    我将为这两个方面添加示例:

    类型错误:

    10 + 'a'
    

    值错误:

    int("hello")
    
        4
  •  1
  •   adi    6 年前

    我想对David的答案再补充一点。

    当我们向函数传递错误数量的参数时,也会发生TypeError。

    如:

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

    这也会导致TypeError:

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