Fix Python ValueError: invalid literal for int() with base 10

Imagine you’re trying to convert a string, say "786xyz", into an integer using Python’s int() function. However, when you run the code, Python throws an error: ValueError: invalid literal for int() with base 10. This error occurs because Python’s int() function expects a string that contains only numeric characters, but you’ve provided a string with non-numeric characters. In this article, we’ll look at why this error occurs and explore quick ways to fix it.

When Does The ValueError Occur?

The error ValueError: invalid literal for int() with base 10 can happen in several situations, including:

  • Trying to convert a string with letters or symbols into an integer.
  • Converting a floating-point number stored as a string.
  • Receiving unexpected input from a user or a file.
  • Parsing data incorrectly.
ValueError invalid literal for int() with base 10

Why Does The ValueError Specifically Mention “base 10”?

base 10 refers to the standard decimal number system that we use in everyday life. When Python tries to convert a string to an integer, it assumes you’re working in base 10 unless you specify a different base. If the string contains anything that’s not a number, Python cannot interpret it as a valid base-10 number, resulting in the ValueError error.

ValueError: invalid literal for int() with base 10 – Causes and Fixes

1. When Converting Non-Numeric Characters

If you try to convert a string containing letters or special characters into an integer, Python won’t understand it and will throw a ValueError error.

Example Error

Here, the variable value contains non-numeric characters "786xyz". When we try to convert the value into an integer, it raises a ValueError.

value = "786xyz" # Containes non-numeric characters
number = int(value)  # Output: ValueError: invalid literal for int() with base 10

The Fix

To fix this error, we can use the .isdigit() method, which checks whether the string consists only of digits (integers). If it does, the value is converted into an integer and assigned to number, then printed. Otherwise, an error message is displayed.

value = "786xyz"

if value.isdigit():  # Check if the value is a digit
    number = int(value) # Convert the value into an integer
    print("Converted:", number)  
else:  
    print("Invalid input: Not a number")

Output

Invalid input: Not a number

2. When Converting Decimal Points

Sometimes, numbers with decimal points are stored as strings, and Python doesn’t allow direct conversion from a string containing a decimal number to an integer.

Example Error

In this example, value contains a decimal number. When we try to convert it directly using int(), it raises the ValueError.

value = "12.34" # Contains a decimal number
number = int(value)  # Output: ValueError: invalid literal for int() with base 10

The Fix

To fix this error, we first convert the string into a float and then into an int using a try-except block. Inside the try block, the number is first converted into a float and then into an integer using int(float(value)). If the conversion fails, the except block handles the error gracefully.

value = "12.34"

try:
    number = int(float(value))  # First convert the string into a float, then into an int
    print("Converted:", number)
except ValueError:
    print("Invalid input")

Output

Converted: 12

3. When Converting an Empty String

An empty string ("")has no numeric value, so converting it to an integer will cause the ValueError: invalid literal for int() with base 10 error.

Example Error

In the example below, value is an empty string. When we try to convert it into an integer, it raises a ValueError.

value = ""
number = int(value)  # Output: ValueError: invalid literal for int() with base 10

The Fix

To fix this error, we first remove unnecessary spaces from the string using .strip() method, then apply an if-else condition to check if the string is empty. If it is not empty, it is converted into an integer; otherwise, an error message is displayed.

value = ""

if value.strip():  # Remove unnecessary spaces
    number = int(value)
    print("Converted:", number)
else:
    print("Invalid input: Empty string")

Output

Invalid input: Empty string

4. When Converting User Input

If you take user input with input(), there’s a high chance of receiving non-numeric data, which can lead to a ValueError.

Example Error

In this example code, If the user enters an invalid input, such as non-numeric characters or a decimal value, a ValueError will occur.

value = input("Enter a number: ")  
number = int(value)  # Will raise ValueError if the user input is invalid

The Fix

We can easily fix this issue using a try-except block to handle incorrect input. The try block attempts to convert the input, and if it fails, the except block catches the ValueError and prompts the user to enter a valid number.

value = input("Enter a number: ") # Get user input

try:
    number = int(value)
    print("You entered:", number)
except ValueError:
    print("Invalid input! Please enter a valid number.")

Output

Assuming the user inputs the string 20:

You entered: 20

Conclusion

In this article, we learned how to fix Python ValueError: invalid literal for int() with base 10 error. Here’s a quick recap:

  • If the string contains letters or symbols, use .isdigit() to check if it contains only numbers before conversion.
  • To convert a decimal number (stored as a string), first convert it into a float using float(), then into an integer using int().
  • An empty string cannot be converted into an integer. Always check if it is empty before conversion to prevent a ValueError.
  • Never trust user input. Use a try-except block to catch errors and prompt the user for valid input.

For more Python tutorials, check out the Python Series on Syntax Scenarios and level up your coding skills!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top