ValueError: invalid literal for int() with base 10: ‘C’
Check if a Python list contains integers, but executing the code results in a "ValueError: invalid literal for int() with base 10: 'C'" error in the terminal.
I want to check weather a Python list is having integer or not. But when try to execute the following code, it gives “ValueError: invalid literal for int() with base 10: ‘C’” error.
ar = ['50', '2', 'C', 'D', '+']
for a in ar:
if int(a):
print(a)
Why is This Error?
The error message “ValueError: invalid literal for int() with base 10: ‘C’” in Python indicates that you are trying to convert the string ‘C’ to an integer using the int()
function, but the string does not represent a valid integer in base 10.
Here’s a breakdown of the key components of the error message
ValueError: This is a built-in exception in Python that is raised when a function receives an argument of the correct type but with an invalid value.
invalid literal for int(): Specifies that the value being passed to the int()
function is not a valid literal that can be converted to an integer.
with base 10: Indicates that the conversion is being attempted in base 10, which is the default base for integer representation.
‘C’: Specifies the problematic value that is causing the error. In this case, the string ‘C’ is not a valid representation of an integer.
To address this error, consider the following steps
Check Input Data: Examine the data that you are trying to convert to an integer. In this case, the string ‘C’ is not a numeric value that can be converted to an integer.
Ensure Valid Input: Make sure that the input data provided to the int()
function is a valid numeric literal that can be converted to an integer in base 10. Valid literals include numbers such as ‘123’, ‘-45’, ‘0’, etc.
Example:
try:
value = int('C')
except ValueError as e:
print(f"Error: {e}")
Handle Invalid Cases: If the data can potentially include non-numeric values, implement proper error handling to deal with such cases. You can use a try-except
block to catch the ValueError
and handle it gracefully.
Example:
try:
value = int('C')
except ValueError as e:
print(f"Error: {e}. The input is not a valid integer.")
# Handle the error condition appropriately.
By ensuring that you are trying to convert valid numeric literals to integers and handling potential errors using try-except
blocks, you can address the “ValueError: invalid literal for int() with base 10: ‘C’” in your Python code.
Comments
-
Danielle Carline
Posted on
Instead of using int() method, you can use isnumeric() or isdigit() methods like this.
ar = ['50', '2', 'C', 'D', '+', '0.9'] for a in ar: if a.isdecimal(): print(a)
or
ar = ['50', '2', 'C', 'D', '+', '0.9'] for a in ar: if a.isdigit(): print(a)