ValueError: invalid literal for int() with base 10
Error message
invalid literal for int() with base 10: 'abc'
Quick summary
You passed a value of the correct type but with an invalid content — like converting a non-numeric string to int.
Why this happens
Calling int() or float() on a string that isn't a valid number
Unpacking a sequence with the wrong number of values
Passing an invalid value to a function (e.g., math.sqrt(-1))
Minimal example
age = int("abc") # ValueErrortry:
age = int("abc")
except ValueError:
print("Please enter a valid number")
age = 0int('abc') fails because 'abc' isn't a valid integer. Wrap the conversion in try/except ValueError to handle invalid input.
How to diagnose
Read the error message — it shows the invalid value
Check the input before converting or passing to the function
Use try/except ValueError to handle invalid input gracefully
How to fix
Validate the input before conversion (e.g., str.isdigit())
Use try/except ValueError with a user-friendly message
Fix the source of the invalid value
How to prevent
Validate user input before processing
Use try/except around conversions that might fail
Related Resources
Related Lessons
- Exceptions
ValueError handling.
Related Practice
- Predict try/except
Practice exception handling.