Because in Python (at least in 2.x since I do not use Python 3.x), int()
behaves differently on strings and numeric values. If you input a string, then python will try to parse it to base 10 int
int ("077")
>> 77
But if you input a valid numeric value, then python will interpret it according to its base and type and convert it to base 10 int. then python will first interperet 077
as base 8 and convert it to base 10 then int()
will jsut display it.
int (077) # Leading 0 defines a base 8 number.
>> 63
077
>> 63
So, int('1e1')
will try to parse 1e1
as a base 10 string and will throw ValueError
. But 1e1
is a numeric value (mathematical expression):
1e1
>> 10.0
So int
will handle it as a numeric value and handle it as though, converting it to float(10.0)
and then parse it to int. So Python will first interpret 1e1 since it was a numric value and evaluate 10.0
and int()
will convert it to integer.
So calling int()
with a string value, you must be sure that string is a valid base 10 integer value.
int()
doesn't work on, say,'1.0'
: it is intended for integers. – Thunderousint('hello world')
? It fails for the exact same reason thatint('1e1')
does -int()
parses integer strings, like it says on the tin. – Thunderous1e1
into an interpreter and watch it return10.0
. If that doesn't say "float" to you, trytype(1e1)
and watch it return<class 'float'>
. Of course, the fact that onlyfloat()
, and notint()
, could parse the string'1e1'
is a good indication, as well. – Thunderous