Your program asks for an age. You press Enter a little too fast, and Python stops:
How old are you?
Traceback (most recent call last):
File "main.py", line 1, in <module>
age = int(input("How old are you? "))
ValueError: invalid literal for int() with base 10: ''ValueError: invalid literal for int() with base 10 means int() was given text that doesn't look like a whole number, so it couldn't convert it. The most useful part of the message is at the very end, in quotes: that's the exact text int() received. Here it's '', an empty string, because nothing was typed. This article shows how to read that clue and fix each common case, including the decimal point, the empty line and the stray comma.
Try it yourself
Save this as main.py and run python main.py:
age = int(input("How old are you? "))
print("Next year you'll be", age + 1)Type 31 and it works. Then run it again and try each of these answers: nothing (press Enter), 3.5, twenty, 1,000. Each one gives this error, with different text at the end.
What the error means
Read the last line in parts:
ValueError: the type of the value was right (int()accepts text), but this particular value wasn't usable.invalid literal: the text isn't written like a number. A literal is the way a value is written.for int() with base 10:int()was reading an ordinary decimal number. Base 10 is the default; you only see other bases if you ask for them, likeint("1A", 16).: '': the text it was given, in quotes. This is the clue.
So the question is always the same: why was the text this, and not a whole number?
Cause 1: empty input, ''
ValueError: invalid literal for int() with base 10: ''Two quotes with nothing between them mean an empty string. With input(), it happens when the user presses Enter without typing anything. With files, it often comes from an empty line at the end of the file.
The fix is to check before converting, or to ask again (see "The robust fix" below). For files, skip empty lines:
for line in lines:
if line.strip() == "":
continue
numbers.append(int(line))Cause 2: a decimal number, '3.5'
hours = int(input("Hours a day? "))Hours a day? 3.5
Traceback (most recent call last):
File "main.py", line 1, in <module>
hours = int(input("Hours a day? "))
ValueError: invalid literal for int() with base 10: '3.5'int() reads whole numbers only. It won't guess that you're happy to lose the .5. You have two options, depending on what you need:
print(float("3.5"))
print(int(float("3.5")))3.5
3- If decimals are allowed, use
float()and keep them. - If you really want a whole number, convert to
floatfirst and then toint. Note thatint()cuts off the decimals, it doesn't round:int(float("3.9"))is3. Useround()if you want rounding.
The same happens with prices read from text: int("12.99") fails with '12.99' at the end.
Cause 3: words instead of digits, 'twenty'
ValueError: invalid literal for int() with base 10: 'twenty'int() only understands digits, with an optional + or - in front. Words aren't numbers to it. You can't fix this in the code; you can only handle it: ask again, or show a message. See "The robust fix".
Cause 4: commas, currency signs and units, '1,000'
ValueError: invalid literal for int() with base 10: '1,000'People write numbers with thousands separators, currency signs and units: 1,000, €20, 5kg. int() accepts none of these. Clean the text first:
amount = int(text.replace(",", ""))Be careful in international programs: in many countries, 1,5 means one and a half, not fifteen. If you accept numbers from people in different countries, decide on one format and tell the user.
Underscores are the one exception: Python accepts int("1_000") and gives 1000, because underscores are allowed in Python's own number syntax.
Cause 5: hidden characters from files and splits
Spaces and line breaks around the number are fine: int(" 42 ") gives 42, and so does int("42\n"). But when you split a line of text, the pieces can contain more than you think:
line = "Sam,31\n"
name, age = line.split(",")
print(repr(age))
print(int(age))
price = "12.99"
print(int(price))'31\n'
31
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(int(price))
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '12.99'repr() shows the exact text, including invisible characters like \n. It's a reliable way to see what int() really receives. In this case the \n was harmless, but in real files you may find a label like 'Age' in the header row, quotes around the number, or a column you didn't mean to read.
Header rows in CSV files
A very common case: you read a CSV file and convert every row, including the first one with the column names. The error ends with the header text, for example : 'age'. Skip the first line, or use the csv module's DictReader, which treats the header as names.
The robust fix: try and except
For input from people, you can't prevent bad answers, so catch the error and ask again:
while True:
text = input("How old are you? ")
try:
age = int(text)
break
except ValueError:
print("Please type a whole number, like 31.")
print("Next year you'll be", age + 1)How old are you?
Please type a whole number, like 31.
How old are you? abc
Please type a whole number, like 31.
How old are you? 12
Next year you'll be 13try runs the conversion. If it raises a ValueError, the program jumps to except, prints a friendly message and loops. When the conversion works, break leaves the loop.
What about isdigit()?
You'll often see if text.isdigit(): as a check before int(). It works for simple cases, but it rejects some valid numbers:
print("42".isdigit(), "-5".isdigit(), "3.5".isdigit(), "".isdigit())True False False False-5 is a valid whole number, but isdigit() says no. try/except asks int() itself, so it's always consistent with what int() accepts.
Errors that look alike
ValueError: could not convert string to float: 'abc': the same problem withfloat().TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType':int()gotNoneinstead of text. That's a different bug: see 'NoneType' object is not subscriptable for how to trace where aNonecame from.TypeError: unsupported operand type(s) for -: 'int' and 'str': you forgotint()entirely. See unsupported operand: 'int' and 'str'.- Java's
NumberFormatException: For input string: the same idea in Java, fromInteger.parseInt.
Wrong fixes that don't help
int(text or 0)for every input. It hides empty answers by silently turning them into0, which might be a real, wrong age.- A bare
except:that catches everything. CatchValueErrorspecifically, so other bugs still show up. - Removing every non-digit character.
"3.5"becomes35, and"-5"becomes5.
A debugging walkthrough
A program that totals numbers from a file fails with invalid literal for int() with base 10: 'Amount':
- Read the text at the end:
'Amount'. That's a word, so it's not from a number row. - Ask where that word lives: the header row of the file.
- Skip the header: read the first line separately, or start the loop from the second line.
- Run again. If a new message ends with
'', an empty line is next: skip lines whereline.strip()is empty. - Add a
print(repr(value))before the conversion if the text in the message still surprises you.
Practice
Predict the result of each.
int(" 7 ")int("7.0")int(float("7.9"))
Answers. (1) 7: surrounding spaces are allowed. (2) invalid literal for int() with base 10: '7.0': a decimal point, even with a zero after it. (3) 7: float gives 7.9, and int cuts off the decimals.
Frequently asked questions
What does "invalid literal for int() with base 10: ''" mean?
int() received an empty string. Usually the user pressed Enter without typing, or a file has an empty line.
How do I convert '3.5' to an integer in Python?
Use int(float("3.5")) for a cut-off whole number, or round(float("3.5")) to round. Keep it as float("3.5") if decimals matter.
What does "base 10" mean?
The number system int() uses to read the text: ordinary decimal digits 0 to 9. It's the default.
How do I check if a string is a number in Python?
Try to convert it with int() or float() inside try/except ValueError. That's more reliable than isdigit().
Is this error the same in older Python versions?
Yes. The message invalid literal for int() with base 10 is the same in Python 3.8 and in current versions.
A quick checklist
- Read the text in quotes at the end of the message.
- Empty (
'')? Handle empty input or skip empty lines. - A decimal? Use
float(), orint(float(...)). - Commas, signs or units? Clean the text first.
- Input from people? Use
try/except ValueErrorand ask again.
For a method that works on any error, read how to read an error message. The Python documentation describes exactly what int() accepts.
