Last modified: May 19, 2025 By Alexander Williams

Fix ValueError: Invalid Literal for int() in Python

Python's int() function converts a string or number to an integer. But sometimes, it raises ValueError: invalid literal for int() with base 10. This error occurs when the input cannot be converted to an integer.

What Causes This Error?

The error happens when int() gets a value it can't convert. Common causes include:

  • Passing a string with letters or symbols.
  • Using empty strings or whitespace.
  • Providing a float as a string without proper handling.

For more details, see Common Causes of ValueError in Python.

Example 1: Non-Numeric String

This code tries to convert a word into an integer:

 
number = int("hello")
print(number)


ValueError: invalid literal for int() with base 10: 'hello'

The error occurs because "hello" is not a number. int() only works with numeric strings.

Example 2: Empty String

An empty string also triggers this error:

 
number = int("")
print(number)


ValueError: invalid literal for int() with base 10: ''

An empty string has no numeric value. Always check for empty inputs.

Example 3: Float as String

This code fails because the string contains a decimal point:

 
number = int("3.14")
print(number)


ValueError: invalid literal for int() with base 10: '3.14'

To fix this, first convert to float, then to int:

 
number = int(float("3.14"))  # Works: converts to 3
print(number)

How to Handle This Error

Use try-except blocks to catch the error. This prevents crashes and allows graceful handling:

 
try:
    number = int("123abc")
except ValueError:
    print("Invalid number! Please enter digits only.")

Learn more about handling this in Handle ValueError Exception in Python.

Input Validation

Always validate user input before conversion. Check if the string is numeric:

 
user_input = "123"
if user_input.isdigit():
    number = int(user_input)
else:
    print("Invalid input!")

This ensures only valid numbers get converted.

Conclusion

The ValueError: invalid literal for int() occurs when converting invalid strings to integers. Always validate inputs and use error handling. For a deeper understanding, read Understanding ValueError in Python.

By following these practices, you can avoid this common Python error and write more robust code.