How to Fix "ValueError: invalid literal for int() with base 10: '' Error in Python?
The "ValueError: invalid literal for int() with base 10: ''" error in Python occurs when you try to convert an empty string or a non-numeric string into an integer using the int() function. To fix this error, you can use the following methods:
- Check for empty or non-numeric strings:
You can check if the string is empty or non-numeric before trying to convert it into an integer. You can use the isnumeric() function to check if the string is numeric or not.
Example:
num = input("Enter a number: ")
if num.isnumeric():
num = int(num)
print(num)
else:
print("Invalid input")
- Use Try-Except block:
You can use a try-except block to catch the ValueError. In the except block, you can print an error message or perform any other action.
Example:
num = input("Enter a number: ")
try:
num = int(num)
print(num)
except ValueError:
print("Invalid input")
In both examples, we are checking if the input is numeric or not, and if it is not numeric, we are printing an error message.