Why does float('string') raise a ValueError rather than TypeError? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Why does float('string') raise a ValueError rather than TypeError?

Hi, I'm asking a question about Python3. If you run float('string'), you will get a prompt as below: ValueError: could not convert string to float: 'string' I understand that string type is unable to be converted into float type, but shouldn't it be TypeError instead of ValueError? Why is it ValueError? As far as I understand, ValueError is the exception that occurs when the type of argument is correct, but the type itself is invalid (e.g. the index of a list is out of boundary), while TypeError is the exception for the wrong type. Can anyone give a clue? Really can't figure it out...

12th Sep 2017, 1:00 AM
Yang Xudong
Yang Xudong - avatar
5 ответов
+ 2
hmm.. how to describe this.. it can be somewhat like layers.. checking of value above (or earlier triggered) than typical.. typical error might somewhat occur in : float a; string b; a=b; and besides , see the code "float('string')" , it focused / forced to check "what's inside the (...) first" , which is inside (...) we call value rather than bother comparing the type.. the "silly" logic in this case is , we give a present box to float , the float won't bother if inside the present box is another float creature or not isn't it !? float focus to see what value inside present box.. afterward float saw what's inside , it may check whenever the value (what inside present box) is float or not , surprise !
12th Sep 2017, 1:15 AM
Mikhael Anthony
Mikhael Anthony - avatar
+ 1
Thanks, Tony! That makes more sense to me. As I am recalling scenarios where TypeError takes place, the only situation that I come up with so far is to add a string and an integer. 🤔 It's confusing but worth working out, as it's essential for handing exceptions, isn't it?
12th Sep 2017, 1:41 AM
Yang Xudong
Yang Xudong - avatar
0
because I am not an indigene of that country I mean, float is a number type and not char or string type
12th Sep 2017, 12:52 AM
Nura Programmer
Nura Programmer - avatar
0
if he is trying to cast a string to a float type, then he might be wrong since he fast normal text not the variable name
12th Sep 2017, 1:20 AM
Nura Programmer
Nura Programmer - avatar
0
@Yang Xudong well , yes , it does feed our curious.. :)
12th Sep 2017, 5:44 AM
Mikhael Anthony
Mikhael Anthony - avatar