ValuePython Error

ValueError

ValueError: invalid literal for int() with base 10: 'abc'

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    age = int(input("Enter age: "))  # user types "twenty"
ValueError: invalid literal for int() with base 10: 'abc'

What causes this error

A string was passed to int() that does not represent a valid integer in the specified base. The string may contain letters, decimal points, spaces, or be empty.

How to fix it

Validate input before conversion. Use try/except ValueError around int(). Use float() first for decimal strings, then convert to int. Strip whitespace with .strip(). Use .isdigit() for simple validation.

Code that causes this error

Broken
age = int(input("Enter age: "))  # user types "twenty"

Fixed code

Fixed
while True:
    text = input("Enter age: ").strip()
    try:
        age = int(text)
        break
    except ValueError:
        print(f"'{text}' is not a valid integer")

About ValueError

This ValueError is raised when `int()` is called with a string that cannot be parsed as an integer. The string must contain only digits (with an optional leading + or -) for the conversion to succeed. Common triggers include passing strings with decimal points (use `float()` first), strings with whitespace or special characters, empty strings, and user input that has not been validated.

The error message includes both the base (usually 10) and the problematic string, making it easy to see what went wrong. For parsing strings that might be floats, use `int(float(s))` to handle decimal points. For hex strings, specify `base=16`.

For robust input parsing, validate the string format first with `.isdigit()`, use `try/except ValueError`, or use regular expressions for complex formats.

Common scenarios

1

Converting user input strings to numbers without validation

2

Unpacking iterables with an unexpected number of elements

3

Passing out-of-range values to mathematical functions

4

Processing data files with inconsistent or malformed records

Related errors