FULL PYTHON FIX · 8 MIN READ
How to Fix ValueError: invalid literal for int() in Python
int() can parse a valid whole-number string, but text such as '12.5' is not an integer literal. Inspect the actual input, validate the intended format, and test the edge cases.
Quick fix
Strip the surrounding whitespace, then call int() inside a narrow try block.
def parse_ticket_count(text):
try:
count = int(text.strip())
except ValueError:
return None
return count if count >= 0 else None
print(parse_ticket_count(' 12 '))
print(parse_ticket_count('12.5'))
print(parse_ticket_count('-2'))Video guide: How to Fix ValueError: invalid literal for int() in Python
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Here is a very common Python error. A form asks for a ticket count. The user enters twelve point five, and our program passes that text to int. Run it before making any edits. The result is not twelve and it is not thirteen. Python raises ValueError and says the literal for int is invalid. The final part of the message shows the exact text it tried to parse: twelve point five. This matters because input from a terminal, a form, or a CSV field is often text even when it looks numeric. The variable name tickets text does not make the content an integer. The call to int must interpret the characters, and a decimal point is not part of a whole-number literal here.
- 00:45
Notice the assignment to tickets never finishes, so the later print is never reached. We will inspect the input, decide what the application actually accepts, and then implement a rule that preserves a valid zero but rejects decimal text. Do not rush to convert through float; that would change the meaning of the input. The useful debugging question is, what precise characters reached int? Printing the value normally can hide surrounding spaces. repr puts quotation marks around the string, so we can see the spaces around twelve. In this diagnostic, int accepts that whitespace and also accepts a leading plus sign.
- 01:25
It rejects the decimal point. The exception handler catches only ValueError so we can continue to the next sample. If a real application expects fractional quantities, the solution is not to keep pretending they are integer counts. It needs a documented decimal rule, perhaps using Decimal for money or another appropriate representation. But tickets are discrete, so twelve point five tickets is invalid. A tempting expression is int of float of text. Try it mentally: twelve point five becomes twelve, with no warning that half a ticket disappeared. Large numeric text can also lose precision when routed through a float.
- 02:06
That is why the data rule must come before the conversion shortcut. The diagnosis also tells us that blank text and words are separate invalid cases we should test explicitly. We now define a small function whose contract is clear: a nonnegative whole-number string produces an integer, and invalid input produces None. Strip removes surrounding whitespace, although int would also accept it; here it makes the input boundary explicit. The try block contains the one operation expected to raise ValueError. The except block returns None only for that conversion error. We are not using a bare except, because that could hide an unrelated bug.
- 02:49
After conversion succeeds, a second rule rejects negative ticket counts. That is a domain decision, not something int can know. Run the calls. Twelve with spaces becomes twelve. Decimal text becomes None. Negative two also becomes None. The last two results have different causes, but the caller can give the same validation message. Importantly, zero must remain an integer zero and not be confused with invalid input. If you use `if not count` to detect an error, zero is false and you would reject a valid zero-ticket value. The caller should use `is None` to distinguish the sentinel from a real integer.
- 03:32
One successful input would not prove this function correct. We test a normal count, zero, whitespace, decimal text, blank text, and a negative count. The results reflect the stated contract rather than whatever int happens to accept. Seven, zero, and eight become integers. A decimal is not truncated. An empty string does not become zero. A negative value is parsed successfully by int, but our application rejects it afterward. This separation is valuable when the input rule changes: perhaps another use case allows negative temperatures, but the ticket-count parser still should not. If your real input source might pass None or an arbitrary object instead of a string, validate that type in an outer layer or deliberately extend this function and its tests.
- 04:23
Do not quietly catch every exception and declare all failures to be user mistakes. A test for malformed text should make it obvious which values are accepted. On the companion guide, every snippet is runnable and the checked exercise asks you to write a similar parser. Compare the displayed outputs with your predictions before moving to the quiz. Your task is to write parse count for nonnegative whole-number strings. It must return five for a string with spaces, zero for the character zero, and None for five point five or negative one. Add your own tests for a word and for an empty string. The main trap is treating zero as if it were missing.
- 05:05
Another trap is converting through float and silently discarding a fractional part. Keep the try block narrow, catch ValueError from the integer conversion, then apply the nonnegative rule. This is a useful pattern anywhere text crosses into a program's typed data: inspect the original text, parse only the format you claim to support, and validate the meaning afterward. If you see invalid literal for int again, start with repr of the input to reveal what was actually passed. The exception is a precise clue about a failed conversion, not a reason to replace all questionable inputs with zero. The PythonLessonLab guide links to the input and exception lessons for the underlying concepts.
- 05:50
Run your parser there, use the automatic task check, and then explain in your own words why twelve point five is not an acceptable ticket count.
Run the conversion with a decimal string
A form asks for a number of tickets, and the program converts its text to an integer. Run the example with '12.5'. The traceback ends in ValueError: invalid literal for int() with base 10: '12.5'. The conversion fails before the result can be assigned. It is the characters in the string, not the variable name, that determine whether int() can parse it.
This error also appears with words such as 'twelve', empty strings, and unexpected punctuation. The built-in input() function returns a string, even when a person types digits. A useful first step is to reproduce the precise value that reached int() instead of assuming the person typed what the prompt requested. Here the intended domain is a nonnegative whole ticket count, so a decimal number should not be silently accepted.
tickets_text = '12.5'
tickets = int(tickets_text)
print(tickets)ValueError: invalid literal for int() with base 10: '12.5'Inspect the exact characters before parsing
Print repr(text) to reveal leading spaces, an empty string, or other characters that a plain print can hide. int() accepts surrounding whitespace and an optional sign, so ' 12 ' and '+12' work. The decimal point is the decisive difference in our example. Keep the displayed input separate from the converted value while debugging; otherwise the assignment may fail before there is anything useful to inspect.
Do not use int(float(text)) as a general repair. It would turn '12.5' into 12 and silently discard half a ticket, while large values can lose precision through a floating-point conversion. Decide whether your application wants a whole number or a decimal measurement. If decimals are valid, parse with the type appropriate to that domain and document a rounding rule separately. For a count, reject the decimal instead of changing its meaning.
for text in [' 12 ', '+12', '12.5']:
try:
print(repr(text), int(text))
except ValueError:
print(repr(text), 'not an integer')' 12 ' 12
'+12' 12
'12.5' not an integerCatch the conversion error at the input boundary
Strip the surrounding whitespace, then call int() inside a narrow try block. Return a clear missing-or-invalid result when the text cannot be parsed. After parsing, check the domain rule that a ticket count cannot be negative. ValueError from int() addresses syntax; it does not enforce business rules. Keeping those decisions separate makes both error messages and tests easier to understand.
A bare except would hide programming bugs unrelated to the conversion. Catch ValueError specifically, and avoid printing a default count of zero when zero means something different from invalid input. In the example, None means no valid count was supplied. The caller can ask again, show a validation message, or leave the field untouched. It should not mistake None for a real zero-ticket order.
def parse_ticket_count(text):
try:
count = int(text.strip())
except ValueError:
return None
return count if count >= 0 else None
print(parse_ticket_count(' 12 '))
print(parse_ticket_count('12.5'))
print(parse_ticket_count('-2'))12
None
Nonedef parse_ticket_count(text):
try:
count = int(text.strip())
except ValueError:
return None
return count if count >= 0 else None
count = parse_ticket_count('abc')
print('Enter a whole, nonnegative count.' if count is None else f'Tickets: {count}')Enter a whole, nonnegative count.Test the boundary, whitespace, and malformed input
Run cases that represent distinct decisions: a normal whole number, zero, surrounding whitespace, decimal text, an empty string, and a negative number. The same parser should give the same answer regardless of where the text came from. Keep the tests close to the function so a future change does not accidentally start truncating decimals or accepting a negative count.
If the input may be None or another non-string value, validate its type at the application boundary or extend the function contract and its tests. The exercise below assumes strings like input() returns. Be careful with text.isdigit() as a shortcut: it has different rules from int(), including how signs are handled, so it is not a universal substitute for conversion. The actual parse plus a specific ValueError handler is a more direct test of the format you need.
def parse_ticket_count(text):
try:
count = int(text.strip())
except ValueError:
return None
return count if count >= 0 else None
for text in ['7', '0', ' 8 ', '12.5', '', '-1']:
print(repr(text), parse_ticket_count(text))'7' 7
'0' 0
' 8 ' 8
'12.5' None
'' None
'-1' None- Inspect repr(text) before guessing what int() received.
- Reject decimal text when the domain requires a whole count.
- Catch ValueError narrowly and test domain rules after a successful parse.
Practice the fix
Write parse_count(text) for a nonnegative whole-number string. Return its integer value, including zero; return None for blank text, decimal text, words, or negative numbers. Show results for ' 5 ', '0', '5.5', and '-1'.
Need a hint?
Call int(text.strip()) inside try/except ValueError. After a successful conversion, return the number only if it is at least zero. Keep zero distinct from None.
See the failure, fix it, then test the boundary
Load each step into the console below and select Run code. Your draft can be restored after trying a step. Loading a sample does not complete the practice task.
- 1 · Reproduce the problem
Expected: ValueError: invalid literal for int() with base 10: '12.5'
- 2 · Run the repair
Expected: None, then 12
- 3 · Test an edge case
Expected: Blank and negative text are rejected; zero and surrounding spaces still work.
- Inspect repr(tickets_text) to see the decimal point that int() receives.
- A ticket count is a whole number. Do not hide the problem with int(float(text)).
- Catch ValueError around int(text.strip()), then check that the parsed count is nonnegative.
Need the concept first? Study Input and Output and its checked task
Python console
Ready to runEdit the code and run it in your browser. Examples above can be loaded with Try this example.
Does your code use input()? Add one value per line
Your output appears here.
Write your solution, then select Check practice.
Key takeaways
- int() parses valid whole-number strings; a decimal string such as '12.5' raises ValueError.
- repr(text) reveals the exact characters that reached the conversion.
- Catch ValueError around the conversion and enforce nonnegative counts afterward.
- Test zero separately from invalid input so a missing value is not misreported.