The error ValueError: invalid literal for int() with base 10 occurs when Python's int() function is passed a string that cannot be interpreted as a valid integer.
Common Causes
Non-numeric characters: The string contains letters, symbols, or spaces (e.g.,
"abc","123.45"," 42 ").Floating-point numbers: Strings with decimal points (e.g.,
"5.20") cannot be directly converted to integers.Empty or whitespace-only strings: An empty string (
'') or string with only spaces (" ") is invalid.Scientific notation: Strings like
"3.2e+07"are not valid forint().Non-integer input from user or file: User input or data from a file may not be in the expected format.
Solutions
1. Use float() first, then int()
If the string represents a decimal number, convert it to a float first, then to an integer:
num_str = "5.20"
result = int(float(num_str)) # Output: 52. Use try-except to handle errors gracefully
Wrap the conversion in a try-except block to prevent crashes:
try:
value = int("abc123")
except ValueError:
print("Invalid input: not a valid integer")3. Validate input with isdigit()
Check if the string contains only digits before conversion:
text = "123"
if text.isdigit():
num = int(text)
else:
print("Input is not a valid integer")⚠️ Note:
isdigit()returnsFalsefor negative numbers ("-123") or decimals.
4. Strip whitespace
Remove leading/trailing spaces using .strip():
text = " 42 "
num = int(text.strip()) # Output: 425. Handle empty strings in pandas
When using pandas, avoid astype(int) on columns with empty strings. Use pd.to_numeric() instead:
df['col'] = pd.to_numeric(df['col'], errors='coerce') # Converts empty strings to NaNSummary
Always ensure the input string is a valid integer representation before calling int(). Use float() + int() for decimals, try-except for safety, and strip() or isdigit() for validation.
The error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.
In the case described in the question, the input was an empty string, written as ''.
Here is another example - a string that represents a floating-point value cannot be converted directly with int:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Instead, convert to float first:
>>> int(float('55063.000000'))
55063
Answer from FdoBad on Stack OverflowThe error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.
In the case described in the question, the input was an empty string, written as ''.
Here is another example - a string that represents a floating-point value cannot be converted directly with int:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Instead, convert to float first:
>>> int(float('55063.000000'))
55063
The following work fine in Python:
>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0
However, passing the string representation of a float, or any other string that does not represent an integer (including, for example, an empty string like '') will cause a ValueError:
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
To convert the string representation of a floating-point number to integer, it will work to convert to a float first, then to an integer (as explained in @katyhuff's comment on the question):
>>> int(float('5.0'))
5
While trying to convert an input string into an integer, I got a Traceback and an error saying 'ValueError: invalid literal for int() with base 10:<string>'. for context, here's the code I was trying to run --
x = None
print("FINDING THE SMALLEST NUMBER from 90, 7089, 54, 678, 6703, 12, 5544, 8989, 9099, 746, 389, 34, 22, 909, 8787, 9976, 543, 898, 9098, 4784")
for ival in [90, 7089, 54, 678, 6703, 12, 5544, 8989, 9099, 746, 389, 34, 22, 909, 8787, 9976, 543, 898, 9098, 4784]:
if x == None:
x = ival
elif ival < x:
x = ival
print("The smallest number has been succesfully found!")
print("Type 'Yes' to view it, and 'No' to not view it.")
red = int(input("Enter here: "))
if red == Yes:
print(x)
elif red == No:
print("Fine then...")
else:
print("Please enter a valid input.")I tried to fix the issue by first converting the string to a float and then an int, but it still didn't work. Tried searching for a solution on the net, but the only option I could find was a try-except block. And I don't wanna use that. I just want to fix this so that, I type 'Yes' and it shows me the number. But I am still a newbie in all this and don't know that much, tbh.
Videos
I spent way too long working this one out, so here it is:
This was a test for if I can run a function through a function, and it gets the total of a list.
file = open("numbers.txt", "r")
read_file = file.read()
def iterate_through_file(f, fx):
for c in range(len(f)):
= f[c]
fx(temporary_value_store)
def total(tvs):
tvs = int(tvs)
global running_total
running_total += tvs
#return tvs
#main
running_total = 0
iterate_through_file(read_file, total)
print(running_total)Initially, everything looks fine. Why isn't it working?
The error is passing on the line:
tvs = int(tvs)
But there is nothing wrong with it. The error reads:
ValueError: invalid literal for int() with base 10: '\n'
We notice it says "\n". This is an invisible character called a whitespace that is essentially saying:
"Don't put the next character here, put it down there, one line below."
In text files, this is also the case. If i had a text file of:
1 2 3 4
There is an invisible:
1\n 2\n 3\n 4
Which tells me to "go down to that next line and put the number there".
So, what python has done is read the list, but included these \n's.
So how do we combat this? Very easy.
Firstly, I am aware of the .strip() method, but the reason that does not work is because it removes only from the START and END of a variable. We are trying to remove from inside the variable.
So we will use the .split() function.
The split function takes a variable and turns it into a list. In our original variable, the variable counted \n as an index. So when we loop through this variable, our second index of 1 will have the string "\n". The error now comes from when we try to cast this from a string to an integer inside the def total().
If we split the variable into a list, the list will ignore the \n. This is because whitespaces are how .split() knows where to split. It will find the \n and look at the string before it, then ignore the \n. Its like if you had a line of bricks you want to count, and you want to mark every 5 bricks with a red one so it makes it easier to count. You wouldn't count the red ones in your total, but they are still there to signify every 5th brick.
SO:
Now we know that the problem is because of the "\n" whitespaces, and we know we can get around it with .split().
We do this by:
file = open("numbers.txt", "r")
read_file = file.read()
lines = []
lines = read_file.split()This creates an array called lines, and splits read_file into it.
We run this, and our code works!
That's the end. Forgive me if I have used incorrect terminology.
Feel free to notify me and I will work on it!
Also please provide feedback if you want to. I am still a historically bad explainer despite a certain commenters words from my last post.
Here is the full code if you want to try it out:
#loop through a file of numbers and find the; total, average, highest and lowest, and how many even and odds there are, using as many robust program concepts as possible
#open file for reading
file = open("numbers.txt", "r")
#read file line by line
read_file = file.read()
lines = []
lines = read_file.split()
#function takes 2 parameters, the read file, and a function
def iterate_through_file(f, fx):
#running_total = 0
for c in range(len(f)):
temporary_value_store = f[c]
fx(temporary_value_store)
#return running_total
def total(tvs):
tvs = int(tvs)
global running_total
running_total += tvs
#return tvs
#main
running_total = 0
iterate_through_file(lines, total)
print(running_total)Also, I know I posted 3 times in like 3 days, but I am not one of those coding guys who cannot figure out a problem without stack overflow and an iced coffee, but still spend all day with a hunchback at their desk coding like it's their job (It probably is).
I felt I needed to say this because posting this much makes me out to be one of those guys. Coding is for fun.
Anyway, hope this helps someone out there!
Have A Good One,
Hawk