Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError and TypeError in python

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'
like image 605
thileepan Avatar asked Jan 19 '18 14:01

thileepan


People also ask

What is an ValueError in Python?

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.

What is TypeError in Python?

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.

How do I fix Python ValueError?

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.

How do you declare a ValueError in Python?

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.


Video Answer


2 Answers

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

like image 197
David Avatar answered Oct 12 '22 15:10

David


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

like image 32
Imad77 Avatar answered Oct 12 '22 15:10

Imad77