ValueError and TypeError in python

thileepan picture thileepan · Jan 19, 2018 · Viewed 9.3k times · Source

I can't completely understand the difference between Type and Value error in Python3x.

Why do we get a ValueError when I try float('string') instead of TypeError? shouldn't this give also a TypeError because I am passing a variable of type 'str' to be converted into 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'

Answer

David picture David · Jan 19, 2018

A Value error is

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value

the float function can take a string, ie float('5'), it's just that the value 'string' in float('string') is an inappropriate (non-convertible) string

On the other hand,

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError

so you would get a TypeError if you tried float(['5']) because a list can never be converted into a float.

Cite