Invalid literal for int() with base 10?

Roel Schroeven roel at roelschroeven.net
Fri May 26 03:43:20 EDT 2023


Op 25/05/2023 om 23:30 schreef Kevin M. Wilson via Python-list:
> Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies a base parameter)?! The picture is of the code I've written... And the base 10 paradigm involved?? years = int('y') # store for calculationValueError: invalid literal for int() with base 10: 'y'What is meant by "invalid literal"? I'm trying to convert srt to int, and I didn't know I needed to specify the base. Plus I haven't read anything that I need to specify the base for the int().
That error message might give the impression that you have to specify 
the base, but that's misleading. It's just trying to be helpful, showing 
what base was used because the allowed values depend on the base. For 
example, these will work:

int('abcd', 16) # abcd is a valid hexadecimal number
int('249', 10)
int('249') # same as above, since base 10 is the default
int('14', 8)

These don't work:

int('abcd', 10) # abcd is not a decimal number
int('abcd') # same as above, since base 10 is the default
int('249', 8) # 249 is not an octal number since 9 is not an octal digit

An error message like "invalid literal for int(): '249'" would be very 
confusing because 249 seems to be a valid integer at first sight; 
""invalid literal for int(): '249' with base 8" makes clear why it's not 
accepted.

-- 
"I love science, and it pains me to think that to so many are terrified
of the subject or feel that choosing science means you cannot also
choose compassion, or the arts, or be awed by nature. Science is not
meant to cure us of mystery, but to reinvent and reinvigorate it."
         -- Robert Sapolsky



More information about the Python-list mailing list