Last updated: Apr 8, 2024
Reading time·5 min
The Python "ValueError: invalid literal for int() with base 10" occurs when we
pass a string that cannot be directly converted to an integer to the int()
class.
Common causes of the error are:
int()
.int()
.Here are 3 examples of how the error occurs.
# ⛔️ ValueError: invalid literal for int() with base 10: '5.0' print(int('5.0')) # ⛔️ ValueError: invalid literal for int() with base 10: '' print(int('')) # ⛔️ ValueError: print(int('a2c3'))
We can't directly pass a string that contains a float to the int()
class
because the class expects a value with base 10 (where each digit can have an
integer value ranging from 0
to 9
- 10 possibilities).
my_str = '5.6' # ✅ Convert to a float first my_float = float(my_str) my_int = int(my_float) print(my_int) # 👉️ 5 print(type(my_int)) # 👉️ <class 'int'>
Another common cause of the error is passing a string that contains non-digit characters to the int() class.
The int()
class expects a string that is a valid integer.
# ✅ a string that is a valid integer my_str = '123456' my_int = int(my_str) print(my_int) # 👉️ 123456
The int()
class parses the string in the example without any issues because:
The error is often raised when you pass a string that contains non-digit
characters to the int()
class.
my_str = 'a2c3' # ⛔️ ValueError: invalid literal for int() with base 10: 'a2c3' print(int(my_str))
When taking user input with the input()
function, the value is always going to
be converted to a string, even if the user enters an integer.
Therefore, we have to use the int()
class to convert the string values to
integers.
num_1 = int(input('Enter a number: ')) num_2 = int(input('Enter another number: ')) result = num_1 + num_2 print(result)
However, as shown in the gif
, this can cause issues if the user enters a value
that is not a valid integer.
You can use a try/except statement to handle the error.
try: num_1 = int(input('Enter a number: ')) num_2 = int(input('Enter another number: ')) result = num_1 + num_2 print(result) except ValueError: print('Invalid integer value supplied.')
The code sample uses a try/except
statement to handle the error.
If the user provides an invalid integer, the call to the int()
class raises a
ValueError
and the except block is run.
The error is handled in the except
block, so it no longer crashes the program.
If taking floating-point numbers from user input,
use the float()
class in the place of int()
.
If your string is a valid floating-point number, convert the string to a float
before passing it to the int()
class.
my_str = '5.6' my_float = float(my_str) my_int = int(my_float) print(my_int) # 👉️ 5 print(type(my_int)) # 👉️ <class 'int'>
The float()
class takes care of converting the string to a floating-point
number and the int()
class converts the float to an integer.
When the floating-point number is passed to the int()
class, it gets
truncated.
If you need to round the float to an integer, use the:
round()
function to round to the nearest integer.my_str = '5.6' my_int = round(float(my_str)) print(my_int) # 👉️ 6 print(type(my_int)) # 👉️ <class 'int'>
import math my_str = '5.1' my_int = math.ceil(float(my_str)) print(my_int) # 👉️ 6 print(type(my_int)) # 👉️ <class 'int'>
import math my_str = '5.999' my_int = math.floor(float(my_str)) print(my_int) # 👉️ 5 print(type(my_int)) # 👉️ <class 'int'>
Make sure to print() the value you are
passing to the int
class as it may not contain what you expect.
For example, you might be passing an empty string or a string that contains a
space to the int()
class.
val = ' ' result = int(val.strip() or 0) print(result) # 👉️ 0
The str.strip() method returns a copy of the string with the leading and trailing whitespace removed.
If removing all leading and trailing whitespace from the string returns an empty
string, we pass 0
to the int()
class.
Alternatively, you can use an if/else
statement to check if the string is
empty before passing it to int()
.
my_str = ' ' if my_str.strip(): my_int = int(my_str) else: # 👇️ this runs print('The specified string is empty')
The string in the example contains only spaces, so it doesn't pass the test in
the if
statement and the int()
class is never called.
try/except
statement to handle the errorYou can also use a try/except
block to handle the error.
val = 'abc' try: result = int(val) except ValueError: result = 0 print(result) # 👉️ 0
If calling the int()
class with the value raises a ValueError
, the except
block runs where we set the result
variable to 0
.
If you have a string that may also contain characters but you only need to
extract an integer, use the filter()
function to filter out all non-digits.
my_str = 'a40b' my_num_1 = int(''.join(filter(str.isdigit, my_str))) print(my_num_1) # 👉️ 40
The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
The str.isdigit() method returns
True
if all characters in the string are digits and there is at least 1
character, otherwise False
is returned.
We basically check if each character in the string is a digit, return the result
and join the digits into a single string before using the int()
class to get
an integer value.
int()
and float()
classesint()
class can be called with the string representation of an integer.my_str = '12345' my_int = int(my_str) print(my_int) # 👉️ 12345
float()
class can be called with the string representation of a float.my_str = '123.45' my_float = float(my_str) print(my_float) # 👉️ 123.45
float()
class can be called with the string representation of an
integer.my_str = '12345' my_float = float(my_str) print(my_float) # 👉️ 12345.0
int()
class can be called with a floating-point number.my_float = 123.99 my_int = int(my_float) print(my_int) # 👉️ 123
float()
class can be called with an integer.my_int = 1234 my_float = int(my_int) print(my_float) # 👉️ 1234
These are the only valid calls you can make to the int()
and float()
classes
in Python.
To solve the Python "ValueError: invalid literal for int() with base 10" error:
int()
class.float()
class before calling int()
when converting strings that
are floating-point numbers to integers.You can learn more about the related topics by checking out the following tutorials: