In this Python tutorial, we will discuss how to fix the error “ValueError: Invalid literal for int() with base 10” which comes in Python.
ValueError: Invalid literal for int() with base 10
In Python, ValueError is a type of exception raised when a function receives an argument of the correct type but an inappropriate value.
The error message “ValueError: Invalid literal for int() with base 10” specifically comes up when you’re trying to convert a non-integer string into an integer using the int()
function. “Invalid literal for int() with base 10” is Python’s way of saying that the conversion can’t be done since the string doesn’t correctly represent an integer value.
In Python, the int()
function is used to convert a number or string to an integer. If the input is a string, the string should contain decimal numbers. The function assumes that the number in the string is decimal (base 10), hence the ‘with base 10’ in the error message. When the string contains non-numeric characters or is an empty string, a ValueError is raised.
Examples
Consider the following examples that throw the “ValueError: Invalid literal for int() with base 10” error:
Suppose you’re writing a program that asks the user to input two numbers, and then calculates and prints their sum. Here’s a simple implementation:
# Get user inputs
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
# Convert inputs to integers and calculate sum
sum = int(num1) + int(num2)
# Print the result
print("The sum is:", sum)
This program works fine if the user inputs valid numbers. However, if a user were to enter a string that cannot be converted to an integer (for instance, “ABC” instead of “5”), you’d run into a “ValueError: invalid literal for int() with base 10” error. Here’s what that would look like:
How to Fix the Error: invalid literal for int with base 10
Now, let’s talk about how you can handle this error. The first step is to ensure the data you’re converting into an integer is a valid integer. For example, always validate user inputs or data read from files.
Input validation: Make sure the string you are trying to convert only contains numbers. This can be achieved by using Python’s built-in str.isdigit()
function which returns True
if all characters in the string are digits and False
otherwise.
def convert_to_int(input_str):
if input_str.isdigit():
return int(input_str)
else:
print("Invalid input. Please enter a valid number.")
return None
print(convert_to_int("123")) # Output: 123
print(convert_to_int("123a")) # Output: Invalid input. Please enter a valid number. None
Exception Handling: Another method to avoid this error is to use try/except blocks. This way, your program will try to convert the string to an integer and, if a ValueError is encountered, it will execute the code within the except block.
def convert_to_int(input_str):
try:
return int(input_str)
except ValueError:
print("Invalid input. Please enter a valid number.")
return None
print(convert_to_int("123")) # Output: 123
print(convert_to_int("123a")) # Output: Invalid input. Please enter a valid number. None
You can see the output below:
Conclusion
If you will follow any of the approaches, then you will be able to solve the error “valueerror: invalid literal for int() with base 10:”. Also, it solves:
- invalid literal for int() with base 10
- valueerror: invalid literal for int() with base 10: ”
- invalid literal for int() with base 10:
You may also like:
- Remove Unicode characters in python
- Convert a List of Characters into a String in Python
- How to convert an integer to string in Python
- Split a Sentence into a List of Words in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.