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'
What is Python ValueError? Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value. Also, the situation should not be described by a more precise exception such as IndexError.
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.
To resolve the ValueError exception, use the try-except block. The try block lets you test a block of code for errors. The except block lets you handle the error.
ValueError in Python is raised when a user gives an invalid value to a function but is of a valid argument. It usually occurs in mathematical operations that will require a certain kind of value, even when the value is the correct argument.
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
ValueError a function is called on a value of the correct type, but with an inappropriate value
TypeError : a function is called on a value of an inappropriate type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With