+ 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...
5 odpowiedzi
+ 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 !
+ 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?
0
because I am not an indigene of that country
I mean, float is a number type and not char or string type
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
0
@Yang Xudong well , yes , it does feed our curious..
:)