Invalid Literal for int() With Base 10: Complete Python Error Guide
You’re running Python code. Suddenly the error appears: “invalid literal for int() with base 10“. Your code stops. You have no idea what went wrong.
This error is one of the most common Python mistakes. It catches beginners and experienced developers alike. The message is confusing because it doesn’t clearly explain what actually went wrong.
Invalid literal for int() with base 10 is Python’s way of saying you tried to convert something to an integer and it didn’t work. Understanding why it happens and how to fix it saves you from frustration.
Let’s talk about what causes this error and how to solve it.

Understanding the Error Message
The error message itself is cryptic if you’re not familiar with Python internals.
“Invalid literal” means the thing you’re trying to convert isn’t valid for conversion.
“for int()” means you’re using the int() function.
“with base 10” means you’re trying to convert to a base-10 integer, which is the standard integer type.
Put together, the error means: you tried to convert something to a regular integer using int(), and the thing you tried to convert doesn’t look like a number.
The error occurs when you call the int() function with a value that can’t be converted to an integer.
Common Causes
Several situations trigger this error.
Passing a string with non-numeric characters. If you do int(“123abc”), Python can’t convert it. The string contains letters, not just numbers.
Passing a string with spaces. If you do int(” 123″), it might fail depending on whether there are leading or trailing spaces. Sometimes spaces work. Sometimes they don’t.
Passing an empty string. If you do int(“”), there’s nothing to convert. Python doesn’t know what number you want.
Passing a float as a string. If you do int(“123.45”), it fails. The string contains a decimal point, which is valid for floats but not for integers in string form.
Passing None. If you do int(None), it fails. None isn’t a number.
Passing a list, dictionary, or other non-numeric type. If you do int([1, 2, 3]), it fails. Lists aren’t convertible to integers.
Getting user input that’s not a number. If you ask a user to enter a number and they enter “abc”, int() fails when you try to convert it.
These are the main culprits. Understanding which one applies to your situation helps you fix it.
Example: The Classic Mistake
Here’s a common scenario.
You write code to get user input:
user_input = input("Enter a number: ")
number = int(user_input)
The user enters “hello” instead of a number.
Python tries to convert “hello” to an integer. It can’t. The error is raised.
This happens thousands of times per day to Python programmers. It’s so common that it’s almost a rite of passage.
Solution 1: Check the Input
The simplest solution is to check what you’re trying to convert before converting it.
user_input = input("Enter a number: ")
if user_input.isdigit():
number = int(user_input)
else:
print("That's not a valid number")
The isdigit() method checks if the string contains only digits. If it does, conversion is safe.
This works for positive integers. Negative numbers contain a minus sign, so isdigit() returns False for them.
For negative numbers, you need a different approach:
try:
number = int(user_input)
except ValueError:
print("That's not a valid number")
Solution 2: Try-Except Blocks
Try-except is the Pythonic way to handle this error.
try:
number = int(user_input)
except ValueError:
print("Please enter a valid integer")
The try block attempts the conversion. If it fails, the except block runs.
This approach is elegant because it handles any conversion failure, not just specific cases.
You can be more specific:
try:
number = int(user_input)
except ValueError as error:
print(f"Conversion failed: {error}")
This captures the actual error message, which is helpful for debugging.
Solution 3: Validate Before Converting
For more complex scenarios, validate the string before attempting conversion.
def is_valid_integer(value):
try:
int(value)
return True
except ValueError:
return False
if is_valid_integer(user_input):
number = int(user_input)
else:
print("Invalid integer")
This function tests conversion without raising an error. If it converts successfully, you know it’s safe.
Solution 4: Handle Whitespace
Sometimes the issue is whitespace.
user_input = input("Enter a number: ").strip()
The strip() method removes leading and trailing whitespace. This often solves the problem.
Python’s int() function is actually pretty forgiving with whitespace:
int(" 123 ") # This works, returns 123
But other string methods like isdigit() fail with whitespace:
" 123 ".isdigit() # Returns False
Strip the input to avoid confusion.
Solution 5: Handle Floats
If the user might enter decimals, handle them:
try:
number = float(user_input)
if number.is_integer():
number = int(number)
else:
print("Please enter a whole number")
except ValueError:
print("That's not a valid number")
This converts to float first. If it’s a whole number, convert to int. Otherwise, ask for a whole number.
Alternatively, convert the float to int directly:
try:
number = int(float(user_input))
except ValueError:
print("That's not a valid number")
This converts “123.45” to 123. The decimal part is discarded.
Solution 6: Provide Default Values
For optional conversions, provide defaults:
def get_integer(prompt, default=0):
try:
return int(input(prompt))
except ValueError:
return default
age = get_integer("Enter your age: ", default=18)
If conversion fails, the default is used. This is user-friendly because it doesn’t crash.
Solution 7: Use Type Hints and Validation
For more robust code:
def process_number(value: str) -> int:
try:
return int(value)
except ValueError:
raise ValueError(f"'{value}' is not a valid integer")
try:
result = process_number(user_input)
except ValueError as e:
print(f"Error: {e}")
This makes the intent clear and provides helpful error messages.
Solution 8: Strip and Check Multiple Conditions
For bulletproof conversion:
def safe_int_conversion(value):
if not isinstance(value, str):
return None
value = value.strip()
if not value:
return None
try:
return int(value)
except ValueError:
return None
result = safe_int_conversion(user_input)
if result is not None:
print(f"The number is {result}")
else:
print("Could not convert to integer")
This handles multiple cases: non-strings, empty strings, and invalid formats.
Real-World Scenarios
Understanding how this error happens in real code helps prevent it.
Reading from files. If you read numbers from a file as strings and try to convert them, formatting issues cause errors. Trailing spaces or unexpected characters break conversion.
Web scraping. When scraping numbers from web pages, extra whitespace or formatting characters prevent conversion. Always clean the data.
API responses. APIs sometimes return numbers as strings. If they include formatting characters, conversion fails.
Database queries. Some databases return numeric strings. Converting them requires care.
Data processing. In data pipelines, unexpected values slip in. Robust error handling prevents crashes.
Debugging the Error
When you encounter this error, debugging systematically helps.
Print the value you’re trying to convert.
user_input = input("Enter a number: ")
print(f"Input value: '{user_input}'")
print(f"Input length: {len(user_input)}")
print(f"Input repr: {repr(user_input)}")
try:
number = int(user_input)
except ValueError as e:
print(f"Error: {e}")
The repr() function shows exactly what the string contains, including hidden whitespace.
Check the type of the value.
print(f"Type: {type(user_input)}")
Sometimes you’re not converting a string but something else entirely.
Check the encoding.
For text files, encoding issues sometimes introduce weird characters that prevent conversion.
user_input = user_input.encode('utf-8').decode('utf-8')
This ensures proper encoding.
Best Practices to Avoid This Error
Prevention is better than fixing errors.
Always validate user input. Don’t assume users enter what you ask for.
Use type hints. They make intent clear and help catch errors early.
Write defensive code. Assume bad input and handle it gracefully.
Use try-except for conversions. It’s Pythonic and clear.
Strip whitespace from string inputs. It’s a common source of problems.
Test with unexpected inputs. Test what happens with empty strings, special characters, and other edge cases.
Provide clear error messages. When errors occur, tell the user what went wrong.
Key Takeaways
- Invalid literal for int() with base 10 occurs when you try to convert a non-numeric string to an integer.
- The error happens when the string contains non-digit characters, spaces, decimal points, or other non-numeric content.
- Common causes include user input, file data, API responses, and data processing.
- Try-except blocks are the Pythonic way to handle this error.
- Validating input before conversion prevents the error.
- The isdigit() method checks for numeric strings, but doesn’t handle negative numbers or floats.
- Stripping whitespace from input often solves the problem.
- Converting float strings to float first, then to int, handles decimal input.
- Providing default values makes programs more user-friendly.
- Debugging with print statements and repr() reveals exactly what’s causing the error.
- Best practice is to write defensive code that validates input before converting.
- Understanding this error helps you write more robust Python code.
- If you encounter this error, check exactly what you’re trying to convert using repr().
- Use try-except blocks to handle conversion failures gracefully.
- Good error messages help users understand what went wrong and how to fix it.
- This is one of Python’s most common errors, so understanding it makes you a better programmer.