Reputation: 177
Why does float('1.5')
gives 1.5
as output as expected but int('1.5')
gives a value error?
Shouldn't python automatically convert the string into float and then into integer.
Upvotes: 1
Views: 2325
Reputation: 6732
Because 1.5
isn't a valid integer literal which is required by the int()
function.
From the docs:
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.
Whereas integer literals are defined as follows:
integer ::= decinteger | bininteger | octinteger | hexinteger
decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger ::= "0" ("b" | "B") (["_"] bindigit)+
octinteger ::= "0" ("o" | "O") (["_"] octdigit)+
hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
bindigit ::= "0" | "1"
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
Source: https://docs.python.org/3/reference/lexical_analysis.html#integers
Upvotes: 3